Android 以编程方式更改图层列表中的可绘制颜色和形状颜色?
我有这样一个图层列表:Android 以编程方式更改图层列表中的可绘制颜色和形状颜色?,android,android-layout,android-xml,Android,Android Layout,Android Xml,我有这样一个图层列表: <?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" />
<?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/ic_globe
。请将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>
这里R.drawable.border
是我的可绘制,R.id.bg_层
和top_层
是可绘制层列表中项目的id
我希望它对你有用
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*/