我在res/ drawable /my_back背景.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>然后,我将my_background设置为视图上的可绘图,这很好。
但是,我需要从java代码中更改存储在选择器中的layerList中的颜色元素的值。我该怎么做?
我可以在我的视图上调用getBackground(),然后得到一个StateListDrawable,但是我找不到任何方法从StateListDrawable中获取可绘制的子程序。
发布于 2014-02-02 10:13:17
...but我找不到任何方法从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。
发布于 2014-02-02 11:00:02
我不认为您能做到这一点,因为R.java是存储it.Static中所有xml的实例(静态)的文件,这意味着它们需要留在内存中,然后才能动态运行hand.Changing。
https://stackoverflow.com/questions/21461081
复制相似问题