【发布时间】:2020-11-17 10:30:53
【问题描述】:
每次按下“添加按钮”时,我都会向 GridLayout 动态添加一个按钮。 drawble 应用正确,但 style 属性没有应用。
所以我通过参考这篇文章编写了代码,但它并没有按照我想要的方式运行。
https://stackoverflow.com/questions/4738309/how-can-i-change-a-button-style-dynamically-in-android
所以当我搜索时,我发现 setTextAppearance 只能与文本的相关属性一起改变。有什么办法可以改变边距和大小?
我尝试了这种方法以编程方式更改大小,但结果相同。
int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics());
button.setHeight(size);
button.setWidth(size);
我想知道如何动态更改按钮样式或如何将 GridLayout 中的所有单元格设置为相同大小。
我当前的代码
GridLayout gridLayout = (GridLayout) findViewById(R.id.gridLayout);
Button button = new Button(this);
button.setBackgroundResource(R.drawable.color_button_shape);
button.setTextAppearance(R.style.color_button);
GradientDrawable dynamicColor = (GradientDrawable) button.getBackground().getCurrent();
dynamicColor.setColor(Color.parseColor(name));
gridLayout.addView(button);
网格布局
<GridLayout
android:id="@+id/gridLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnCount="3"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0">
</GridLayout>
drawble(color_button_shape)
<shape xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:shape="rectangle">
<corners
android:topLeftRadius="6dp"
android:topRightRadius="6dp"
android:bottomLeftRadius="6dp"
android:bottomRightRadius="6dp" />
</shape>
风格
<style name="color_button">
<item name="android:layout_width">40dp</item>
<item name="android:layout_height">40dp</item>
<item name="android:layout_marginStart">10dp</item>
<item name="android:layout_marginTop">9dp</item>
</style>
I want(请忽略颜色,仅参考尺寸和边距。)
【问题讨论】:
标签: android android-button android-styles android-gridlayout