Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change item drawable color inside layer-list in android

I've created a drawable file with the below code:

    <layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/gray_background"/>
    <item
        android:drawable="@color/light_green"
        android:bottom="@dimen/event_button_bottom_color"/>

</layer-list>

Now at run time, I want to change the second item's drawable color (@color/light_green) with some other color programmatically . How can I do that, please help if anyone know how to achieve this.

Thanks a lot in advanced. :)

like image 699
Prithniraj Nicyone Avatar asked Nov 15 '16 06:11

Prithniraj Nicyone


1 Answers

First add id for item. Find item by id and change color.

<item android:id="@+id/shape_1" android:drawable="@color/gray_background"/>
<item android:id="@+id/shape_2"
    android:drawable="@color/light_green"
    android:bottom="@dimen/event_button_bottom_color"/>

Modify at runtime:

LayerDrawable layerDrawable = (LayerDrawable) getResources()
    .getDrawable(R.drawable.my_drawable);
GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable
    .findDrawableByLayerId(R.id.shape_1);
gradientDrawable.setColor(...);
like image 95
Ahmad Aghazadeh Avatar answered Oct 18 '22 09:10

Ahmad Aghazadeh