Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: changing a color of a layer-list

I've got a layer-list

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="@color/custom_color" />
        </shape>
    </item>
    <item android:top="-2dp" android:right="-2dp" android:left="-2dp">
        <shape>
            <solid android:color="@android:color/transparent" />
            <stroke
                android:width="1dp"
                android:color="@android:color/white"/>
        </shape>
    </item>
</layer-list>

and would like to reuse this drawable in several places in my project, so that @color/custom_color (in the sample above) is replaced in each case with a different one. Instead of creating a separate drawable there should be a way to achieve it. Any ideas?

like image 460
hhg Avatar asked Oct 30 '25 03:10

hhg


1 Answers

This custom_color in rectangle shape must be accessed through an id, say android:id="@+id/shape_rectangle" so define this first in xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/shape_rectangle">
        <shape android:shape="rectangle" >
            <solid android:color="@color/custom_color" />
        </shape>
    </item>
    <item android:top="-2dp" android:right="-2dp" android:left="-2dp">
        <shape>
            <solid android:color="@android:color/transparent" />
            <stroke
                android:width="1dp"
                android:color="@android:color/white"/>
        </shape>
    </item>
</layer-list>

then:

    LayerDrawable shapeRectangle = (LayerDrawable) ContextCompat.getDrawable(context, R.drawable.custom_layer);
    GradientDrawable gradient = (GradientDrawable) shapeRectangle.findDrawableByLayerId(R.id.shape_rectangle);
    gradient.setColor(Color.RED);

replace custom_layer with your drawable's name