如何在drawable中引用颜色属性? [英] How to reference colour attribute in drawable?
问题描述
我想做一个简单的事情:定义一个与系统状态按下背景颜色完全相同的可绘制对象.我在 res/drawables/my_drawable.xml 中这样做:
I would like to do a simple thing: Define a drawable which has exacly same background colour as system state-pressed background colour. I do it like this in res/drawables/my_drawable.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_selected="true">
<color android:color="?android:attr/colorPressedHighlight"/>
</item>
<item android:state_selected="false">
<color android:color="@color/section_list_background"/>
</item>
</selector>
我总是得到:
java.lang.UnsupportedOperationException: Cant convert to color: type=0x2
有什么线索吗?
问候
推荐答案
您可能需要执行以下操作来解决您的问题:
You might need to do the following to fix your problem:
1) 为颜色文件中的每个主题定义 2 种颜色:
1) Define 2 colors for each theme in your colors file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="my_color_dark">#ff33B5E5</color>
<color name="my_color_light">#ff355689</color>
</resources>
2) 使用内容创建文件 res/values/attrs.xml:
2) Create file res/values/attrs.xml with contents:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="my_color" format="reference" />
</resources>
3) 假设你的styles.xml中有2个主题(Theme.dark
和Theme.light
)定义:
3) Assuming you have 2 themes in your styles.xml (Theme.dark
and Theme.light
) define:
<style name="Theme.dark" parent="@style/Theme.Sherlock">
<item name="my_color">@color/my_color_dark</item>
</style>
<style name="Theme.light" parent="@style/Theme.Sherlock.Light">
<item name="my_color">@color/my_color_light</item>
</style>
4) 在可绘制对象中使用颜色:
4) Use the color in a drawable:
<color android:color="?attr/my_color"/>
希望这能解决您的问题.
Hope this should fix your problem.
这篇关于如何在drawable中引用颜色属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!