How to change the color of an element to draw inside a list layer in android

I created a download file with the code below:

    <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 runtime I want to change the second color that can be highlighted (@ color / light_green) with a different color programmatically. How can I do this, please help if anyone knows how to achieve this.

Many thanks in advanced form. :)

+4
source share
1 answer

First add the id for the item. Find the item by ID and change the 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"/>

Change at runtime:

LayerDrawable layerDrawable = (LayerDrawable) getResources()
    .getDrawable(R.drawable.my_drawable);
GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable
    .findDrawableByLayerId(R.id.shape_1);
gradientDrawable.setColor(...);
+4
source

Source: https://habr.com/ru/post/1660750/


All Articles