我有一个像这样的图层列表:
<?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>
如何以编程方式更改形状的颜色以及可绘制的颜色?
例如,如何将颜色更改为#FF0000
并以编程方式将drawable更改为@drawable/ic_globe
?
答案 0 :(得分:0)
请为图层项添加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_layer
和top_layer
是我的可绘制对象的层列表项的ID
希望它对您有用