【问题标题】:Can I override some attribute of drawable shape?我可以覆盖可绘制形状的某些属性吗?
【发布时间】:2015-07-08 08:09:19
【问题描述】:

我有两个按钮,它们的形状相同,只是颜色不同

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 个可绘制的 xml。

我可以只创建一个可绘制的xml,然后覆盖布局xml中的颜色或其他属性吗?

【问题讨论】:

    标签: android android-drawable shapedrawable


    【解决方案1】:

    通过 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);
    

    【讨论】:

    • Tnx。我需要 MaterialTextView 的这个解决方案,并且不得不将 ShapeDrawable 更改为 GradientDrawable。在我的情况下更改 textview 的背景颜色应用此代码(在 kotlin 中): (binding.myTextView.background as GradientDrawable).color = ColorStateList.valueOf(getColorAttr(binding.root.context, R.attr.colorPrimary))跨度>
    最近更新 更多