我在 res/drawable/my_background.xml 中定义了一个 drawable。
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>
然后我将 my_background 设置为可在 View 上绘制并且效果很好。
但是我需要从我的 java 代码更改存储在我的选择器中的 layerList 中的颜色元素的值。我该怎么做?
我可以在我的 View 上调用 getBackground(),然后获取 StateListDrawable,但我找不到任何方法从 StateListDrawable 获取可绘制子级。
最佳答案
...but I can't find any method to get the drawable children from a StateListDrawable.
您可以通过父类(super class) DrawableContainer
的 DrawableContainerState
类访问子级。那个类(class)有一个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
。
关于android - 从java修改一个xml StateListDrawable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21461081/