我正在尝试制作一个选择器,它使用基于主题的颜色作为其背景。根据这个SO答案的说明,我首先在res/values/colors.xml中定义我的颜色可绘制对象:
<color name="selected">#FFF7C9</color>
然后我在res/values/attrs.xml中定义了一个属性:
<attr name="drawable_selected" format="reference" />
然后在我的主题中,我将属性设置为我的颜色可绘制资源(res/values/styles.xml):
<style name="AppThemeWhite" parent="AppTheme">
<item name="drawable_selected">@color/selected</item>
</style>
最后,我在我的选择器中引用了属性(res/drawable/selected_background):
<selector>
<item android:state_activated="true" android:drawable="?drawable_selected" />
<item android:drawable="@android:color/transparent" />
</selector>
当我运行这个程序时,当尝试膨胀使用选择器的类时,我会得到一个错误
Binary XML file line #2: Error inflating class <unknown>
。但是,当我将选择器的state_activated
更改为直接使用android:drawable="@color/selected"
引用可绘制对象时,它可以工作。这是一个错误吗?还是我做错了什么?
编辑
如果我添加一个颜色属性(res/values/attrs.xml)
<attr name="selected_color" format="color" />
并在我的主题中定义颜色(res / values / styles.xml)
<item name="selected_color">#FFF7C9</item>
我可以通过更改颜色资源(res/values/colors.xml)来更改可绘制对象的颜色。
<color name="selected">?selected_color</color>
我希望通过在选择器中直接使用android:drawable="@color/selected
"引用可绘制对象。但是这样会导致崩溃!将颜色可绘制对象改回硬编码的值#FFF7C9
可以解决问题。看来整个主题系统都有些问题...