在运行时更改作为背景使用的Drawable XML中的实心颜色形状

29

我有一个可绘制的xml文件(background.xml):

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

    <item android:id="@+id/shape_id">
        <shape android:shape="rectangle">
            <solid android:color="#ffefefef" /> 
        </shape>
    </item>

</layer-list>

由LinearLayout使用:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@drawable/background"
    android:id="@+id/layout_id"
    >

现在我需要根据一些条件在运行时更改 shape_id 的实心颜色。如何做到这一点?


不,我认为这是不可能的。 - Raghunandan
7
不可能不存在。 - AndroidGecko
1个回答

62

我发现了:

    View v = findViewById(R.id.layout_id);

    LayerDrawable bgDrawable = (LayerDrawable)v.getBackground();
    final GradientDrawable shape = (GradientDrawable)   bgDrawable.findDrawableByLayerId(R.id.shape_id);
    shape.setColor(----);

3
你知道如何在 RemoteView 上实现相同的小部件吗?谢谢。 - stuckedoverflow
@MV1 这在远程视图中是可能的。因为它没有起作用。你能指导我吗?http://stackoverflow.com/questions/24545857/how-to-change-remote-view-background-in-runtime?noredirect=1#comment38013228_24545857 - RED.Skull
@ʞᴉɯ,你能帮忙回答一个类似的问题吗?这个问题是关于如何改变ImageButton的形状和颜色:http://stackoverflow.com/questions/35398658/change-the-shape-color-of-a-imagebutton/35399878#35399878 - user5366495

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