首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从java修改xml StateListDrawable

从java修改xml StateListDrawable
EN

Stack Overflow用户
提问于 2014-01-30 15:49:54
回答 2查看 1K关注 0票数 5

我在res/ drawable /my_back背景.xml中定义了一个可绘制的文件。

my_background.xml是:

代码语言:javascript
复制
<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中获取可绘制的子程序。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-02-02 10:13:17

...but我找不到任何方法从StateListDrawable中获取可绘制的子级。

您可以通过超类DrawableContainerStateDrawableContainer来访问子类。该类有一个getChildren()方法,它将返回一个包含两个LayerDrawable的数组。然后,您可以进一步操作可绘制的对象,以达到目标可绘制:

代码语言:javascript
复制
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

票数 12
EN

Stack Overflow用户

发布于 2014-02-02 11:00:02

我不认为您能做到这一点,因为R.java是存储it.Static中所有xml的实例(静态)的文件,这意味着它们需要留在内存中,然后才能动态运行hand.Changing。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21461081

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档