以编程方式在图层列表中更改可绘制对象和形状的颜色?

7

我有一个图层列表,就像这样:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/black" />
        </shape>
    </item>

    <item
        android:drawable="@drawable/ic_pin"
        android:adjustViewBounds="true"
        android:scaleType="fitXY" />
</layer-list>

我该如何以编程方式更改形状和drawable的颜色?
例如,我如何以编程方式将颜色更改为#FF0000并将drawable更改为@drawable/ic_globe
1个回答

6
请在图层的项目中添加id属性,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/bg_layer">
        <shape android:shape="oval">
            <solid android:color="#000000" />
        </shape>
    </item>

    <item
        android:id="@+id/top_layer"
        android:drawable="@drawable/ic_pin"
        android:adjustViewBounds="true"
        android:scaleType="fitXY" />
</layer-list>

Java 编程代码

LayerDrawable bgDrawable = (LayerDrawable) getResources().getDrawable(R.drawable.border);/*drawable*/
GradientDrawable bg_layer = (GradientDrawable)bgDrawable.findDrawableByLayerId (R.id.bg_layer);/*findDrawableByLayerId*/
bg_layer.setColor(Color.RED);/*set color to layer*/
bgDrawable.setDrawableByLayerId(R.id.top_layer,getResources().getDrawable(R.drawable.ic_globe));/*set drawable to layer*/
image.setImageDrawable(bgDrawable);/*set drawable to image*/

这里的 R.drawable.border 是我的可绘制对象,R.id.bg_layertop_layer 是可绘制对象中图层列表项的 ID。希望这对您有用。

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