以编程方式更改<item>属性

5

我正在尝试更改按钮的背景以显示正在运行的后台进程的进度。我使用的是由两种颜色组成的可绘制对象,因此现在我需要以编程方式更改以下层列表中这些<item>的顶部和底部属性:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:bottom="20dp">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>

    <item android:top="30dp">
        <shape android:shape="rectangle" >
            <solid android:color="#000000" />
        </shape>
    </item>
</layer-list>

我无法从Java代码中选择<item>元素并修改它们。
2个回答

0

只需创建具有其他项目值的相同xml文件,并为按钮设置新背景。似乎您无法在运行时更改这些值。


我需要能够设置特定的值,以显示后台任务的当前状态。这不可能使用另一个静态的xml文件来实现。 - alvarovmz

0
改变XML也无济于事,因为Android在运行时不使用它们。相反,请查看 LayerDrawable,因为这是从您的XML创建并在运行时使用的内容。
所以基本上你可以像这样做,并从那里继续: LayerDrawable ld =(LayerDrawable)mButton.getBackground();
然而,更好/更简单的方法可能是创建自己的Drawable类,这将非常简单,因为您只需要绘制两个矩形。

一个自定义的Drawable类是最好的解决方案。 - alvarovmz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接