我正在尝试以编程方式更改可绘制对象中图层的颜色,因此实际的可绘制对象 xml 文件不会更改,而只会更改当前用作 src 的可绘制对象ImageView
。
我正在使用的对象是 3 个圆圈(3 个椭圆形)相互嵌套(见card_template.xml
)。
我有以下代码:
LayerDrawable cardLayers = (LayerDrawable) keyCard.getDrawable();
System.out.println("Number of layers (should be 3): "+ cardLayers.getNumberOfLayers());
GradientDrawable layer1 = (GradientDrawable) (cardLayers.findDrawableByLayerId(R.id.card_layer1));
layer1.setColor(0);
我知道我得到了正确的可绘制对象,因为System.out.println
值,但是当我在 layer1.setColor(0);
中设置图层的颜色时,图层就会消失 - 外圈不再显示在 ImageView keyCard
中。
layer1.setColorFilter(0, PorterDuff.Mode.___)
都没有在任何模式下工作,图层要么保持不变,要么消失。
为什么会这样?我不能在文档中找到我的解决方案,在这里或其他地方
找不到任何问题。请帮忙:)
这是card_template.xml
:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/card_layer1">
<shape android:shape="oval">
<solid android:color="@android:color/black"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<size
android:width="5dp"
android:height="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</shape>
</item>
<item android:id="@+id/card_layer2" android:top="2dp" android:left="2dp" android:right="2dp" android:bottom="2dp">
<shape android:shape="oval">
<solid android:color="#ff0000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<size
android:width="5dp"
android:height="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</shape>
</item>
<item android:id="@+id/card_layer3" android:top="4dp" android:left="4dp" android:right="4dp" android:bottom="4dp">
<shape android:shape="oval">
<solid android:color="#ffffff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<size
android:width="5dp"
android:height="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</shape>
</item>
根据 GradientDrawable 文档 setColor 采用 ColorStateList。
请浏览 ColorStateList 以了解更多信息。 尝试给出一个合适的 ColorState 对象而不是 0。