我定义了以下可绘制的my_background_drawable.xml
:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:gravity="center"
android:shape="rectangle">
<solid android:color="@color/color_stateful" />
</shape>
</item>
<item android:drawable="@drawable/selector_png_drawable" />
</layer-list>
我同时也定义了以下颜色状态列表资源color_stateful.xml
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:color="#FF00ff00"/>
<item android:color="#FFff0000"/>
</selector>
当我将给定的
my_background_drawable
作为某个视图的背景时,我无法观察到在我的形状中定义的color_stateful.xml
中的颜色变化,而实际上视图状态已经发生了改变(selector_png_drawable.xml
是一个指示器)。然而,当我按以下方式修改
my_background_drawable.xml
时,一切都很好:<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- This doesn't work
<item>
<shape android:gravity="center"
android:shape="rectangle">
<solid android:color="@color/color_stateful" />
</shape>
</item>
-->
<item>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape android:gravity="center"
android:shape="rectangle">
<solid android:color="#FF00ff00" />
</shape>
</item>
<item>
<shape android:gravity="center"
android:shape="rectangle">
<solid android:color="#FFff0000" />
</shape>
</item>
</selector>
</item>
<item android:drawable="@drawable/selector_png_drawable"" />
</layer-list>
那么,当在ShapeDrawable
中使用ColorStateList
资源时,颜色状态信息是否只是丢失了呢?或者是我的操作有误?
ColorStateList
被正确地解析了。 - keyboardr<shape>
,每个形状仅通过其<solid>
的color
属性不同,然后将原始<shape>
drawable 替换为引用每个<shape>
的StateListDrawable
。这种方法的丑陋可以通过在<shape>
元素中仅使用资源引用(没有硬编码值),并且可以将原始<shape>
保留在drawable-v21
目录中(以便可能完全切换到更高版本)来稍微缓解。blargh - desseim