Can I override some attribute of the drawn shape?

I have two buttons, they have the same shape, only the color is different

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" />

      

If I want to create 100 button with different colors, I need to create 100 xml labels.

Is it possible to create just one xml label and then override the color or other attributes in the xml layout?

+3


source to share


1 answer


Through XML, no, you can't. XML is fixed elements, if you need dynamic processing use Java.

In your specific case, you can try to achieve what you need using Drawable paint and ColorFilter, something like this:



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

      

+3


source







All Articles