我能否覆盖可绘制形状的某些属性?

5
我有两个按钮,它们的形状相同,只是颜色不同。
b1.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="10dp" />
    <stroke android:width="5px" android:color="#000000" />
    <solid
        android:color="#ff0000"/>
</shape>

b2.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="10dp" />
    <stroke android:width="5px" android:color="#000000" />
    <solid
        android:color="#00ff00"/>
</shape>

layout.xml

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/b1"
    android:text="B1" />


<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/b2"
    android:text="B2" />

如果我想创建100个不同颜色的按钮,我需要创建100个drawable xml文件。
我能否只创建一个drawable xml文件,在layout xml文件中覆盖颜色或其他属性?
1个回答

5

通过XML是不行的,XML元素是固定的,如果需要动态处理,请使用Java。

在您的特定情况下,您可以尝试使用Drawable paint和ColorFilter来实现所需的功能,类似于这样:

Button b1 = (Button) findViewById(R.id.button1);
ShapeDrawable sd = (ShapeDrawable) b1.getBackground();
sb.getPaint().setColor(color);
sb.setColorFilter(... something);

谢谢。我需要这个解决方案来处理MaterialTextView,并且必须将ShapeDrawable更改为GradientDrawable。在我的情况下,要更改textview的背景颜色,请应用以下代码(使用kotlin):(binding.myTextView.background as GradientDrawable)。color = ColorStateList.valueOf(getColorAttr(binding.root.context, R.attr.colorPrimary)) - Reyhane Farshbaf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接