user5578746
user5578746

Reputation: 319

Programmatically change drawable and shape color in layer list?

I have a layer list like this:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/black" />
        </shape>
    </item>

    <item
        android:drawable="@drawable/ic_pin"
        android:adjustViewBounds="true"
        android:scaleType="fitXY" />
</layer-list>

How can I programmatically change the color of the shape as well as the drawable?

For example, how can I change the color to #FF0000 and change the drawable to @drawable/ic_globe programmatically?

Upvotes: 6

Views: 3742

Answers (1)

Android Geek
Android Geek

Reputation: 9225

Please Add id attribute to item of layer like below code:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/bg_layer">
        <shape android:shape="oval">
            <solid android:color="#000000" />
        </shape>
    </item>

    <item
        android:id="@+id/top_layer"
        android:drawable="@drawable/ic_pin"
        android:adjustViewBounds="true"
        android:scaleType="fitXY" />
</layer-list>

Code in Java

LayerDrawable bgDrawable = (LayerDrawable) getResources().getDrawable(R.drawable.border);/*drawable*/
GradientDrawable bg_layer = (GradientDrawable)bgDrawable.findDrawableByLayerId (R.id.bg_layer);/*findDrawableByLayerId*/
bg_layer.setColor(Color.RED);/*set color to layer*/
bgDrawable.setDrawableByLayerId(R.id.top_layer,getResources().getDrawable(R.drawable.ic_globe));/*set drawable to layer*/
image.setImageDrawable(bgDrawable);/*set drawable to image*/

Here R.drawable.border is my drawable, R.id.bg_layer and top_layer are ids of items of layerlist in drawable

I hope its work for you

Upvotes: 7

Related Questions