简体   繁体   中英

how to reuse the defined drawable with different colors in xml

Having drawable defined with one color:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="oval">
<corners android:radius="10dip"/>
<solid android:color="#FF7C71BF"/>

and used in layout for some item as:

android:background="@drawable/oval_shape"

if I would like to reuse this drawable in the layout xml at multiple places but with different colors, how to do it? (It could be done in code to reassign the color, just want to see if it is possible to be done using xml).

Here's a solution that only works with Lollipop and later:

Make the color white:

    <solid android:color="#FFFFFFFF"/>

then use backgroundTint and backgroundTintMode attributes on the view:

        <View
            android:backgroundTint="#FF00FF00"
            android:backgroundTintMode="multiply"
            ....

In this example, it would be green.

For KitKat and earlier, those attributes don't exist so you would have to resort to code:

        setColorFilter(Color.GREEN, Mode.MULTIPLY);

Here's a tutorial for this method.

You cant do it in XML believe me.

In java code simply write as below:

View v = findViewById(R.id.view_id);
LayerDrawable bg = (LayerDrawable)v.getBackground();
final GradientDrawable shape = (GradientDrawable)   bg.findDrawableByLayerId(R.id.drawable_id);
shape.setColor([any color]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM