【问题标题】:Programmatically change drawable and shape color in layer list?以编程方式更改图层列表中的可绘制和形状颜色?
【发布时间】:2015-11-18 22:26:38
【问题描述】:
我有一个这样的层列表:
<?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?
【问题讨论】:
标签:
android
android-layout
android-xml
【解决方案1】:
请将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是我的drawable,R.id.bg_layer和top_layer是drawable中layerlist的ids
希望对你有用