我在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>
Run Code Online (Sandbox Code Playgroud)
然后我将my_background设置为可绘制的视图,并且工作正常.
但我需要从我的java代码中更改存储在我的选择器的layerList中的color元素的值.我怎么做?
我可以在我的视图上调用getBackground(),然后获取StateListDrawable,但我找不到任何方法来从StateListDrawable获取可绘制的子项.
Luk*_*rog 12
...但我找不到任何从StateListDrawable获取可绘制子项的方法.
您可以通过DrawableContainerState超类的类访问子节点DrawableContainer.该类有一个getChildren()方法,它将返回一个包含这两个的数组LayerDrawable.然后,您可以进一步操纵那些drawable以获得目标drawable:
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
Run Code Online (Sandbox Code Playgroud)
从KitKat(API级别19)开始DrawableContainerState公开一个getChild()方法,以便您可以LayerDrawable直接检索正确的方法.
| 归档时间: |
|
| 查看次数: |
976 次 |
| 最近记录: |