Change xml StateListDrawable from java

I have a drawable defined in res / drawable / my_background.xml.

my_background.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <layer-list >
            <item android:drawable="@drawable/product_background_1" />
            <item>
                <rotate
                    android:fromDegrees="180"
                    android:toDegrees="180"
                    android:pivotX="50%"
                    android:pivotY="50%"
                    android:drawable="@drawable/product_background_2" 
                    android:id="@+id/need_to_change_this_color_from_java" />
            </item>
            <item><color android:color="#4400aa00"/></item>
        </layer-list>
    </item>
    <item>
        <layer-list >
            <item android:drawable="@drawable/product_background_1" />
            <item android:drawable="@drawable/product_background_2" />
        </layer-list>
    </item>
</selector>

Then I set my_background to be viewable and it works fine.

But I need to change the value of the color element that is stored in the layerList in my selector from my java code. How to do it?

I can call getBackground () on my view and then get StateListDrawable, but I cannot find any method to get drawable children from StateListDrawable.

+4
source share
2 answers

... but I cannot find any method for pushing children out of StateListDrawable.

, DrawableContainerState DrawableContainer. getChildren(), , LayerDrawable. , , :

StateListDrawable sld = (StateListDrawable) theView.getBackground();
DrawableContainerState dcs = (DrawableContainerState) sld.getConstantState();
Drawable[] children = dcs.getChildren();
RotateDrawable target = (RotateDrawable) ((LayerDrawable) children[0]).getDrawable(1); // or use the id
// use target to change the color

KitKat (API- 19) DrawableContainerState getChild(), LayerDrawable.

+11

, , R.java - , () xmls . Static , . .

0

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


All Articles