如何在安卓工作室中以编程方式更改 CardView 的宽度?CardView 是用 XML 编写的



这是我的主活动代码。当按下按钮时,我想从我的活动中更改CardView的宽度,但它不起作用。我也尝试了其他属性,例如,我可以更改CardView的颜色,它起作用很好。但是CardView的宽度和高度属性不起作用。

import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button button;
private CardView cardView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=findViewById(R.id.button);
cardView=findViewById(R.id.cardView);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cardView.setMinimumWidth(20);//HERE IS THE PROBLEM
}
});
}
}

下面是CardView编写的XML文件。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<androidx.cardview.widget.CardView
android:id="@+id/cardView"
android:layout_width="10dp"
android:layout_height="10dp"
android:layout_margin="180dp"
app:cardBackgroundColor="@color/purple_500"
app:cardCornerRadius="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="150dp"
android:padding="8dp"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>

当按钮按下10dp时,我在xml文件CardView的宽度初始值为20dp中尝试反之亦然,但不起作用

(这是不可能的,但当我使用cardView.setRadius();时,当在xml中CardView宽度大于您想要设置的值时,它就可以工作了例如,当CardView的半径最初为20dp时(您希望为10dp,但反之亦然(

我想知道我缺少什么吗?想添加一些实现。。。

卡片宽度是使用LayoutParams设置的。点击添加您的按钮

LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) cardView.getLayoutParams();
lp.width = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getResources().getDisplayMetrics());
cardView.setLayoutParams(lp);

相关内容

最新更新