Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I override some attribute of drawable shape?

I have two buttons, they are same shape, only 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 create 100 drawable xml.

Can I only create one drawable xml, and then override color or other attributes in layout xml?

like image 713
CL So Avatar asked Sep 27 '22 09:09

CL So


1 Answers

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

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

Button b1 = (Button) findViewById(R.id.button1);
ShapeDrawable sd = (ShapeDrawable) b1.getBackground();
sb.getPaint().setColor(color);
sb.setColorFilter(... something);
like image 54
Budius Avatar answered Oct 06 '22 01:10

Budius