如何以编程方式更改图层列表中形状的颜色 (#000000
)?
这是我的图层列表:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#000000" /> // CHANGE THIS COLOR
</shape>
</item>
<item android:left="5dp">
<shape android:shape="rectangle">
<solid android:color="@color/bg" />
</shape>
</item>
</layer-list>
最佳答案
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/gradientDrawble"> // Give id
<shape android:shape="rectangle">
<solid android:color="#000000" /> // CHANGE THIS COLOR
</shape>
</item>
<item android:left="5dp">
<shape android:shape="rectangle">
<solid android:color="@color/bg" />
</shape>
</item>
</layer-list>
然后在你的代码中添加
LayerDrawable layerDrawable = (LayerDrawable) getResources()
.getDrawable(R.drawable.my_drawable);
GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable
.findDrawableByLayerId(R.id.gradientDrawble);
gradientDrawable.setColor(color); // change color
2016 年 10 月更新
getDrawable()
现已弃用,您应该改用 ContextCompat.getDrawable(context, color)
。
另外,如果您通过 findDrawableByLayerId()
获得 LayerDrawable
,那么您必须为此调用 view.setBackground(layerDrawable)
生效。或者,通过 view.getBackground()
实例化 layerDrawable
也可以。
关于android - 以编程方式更改图层列表中形状的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32163918/