我想为我的应用程序选择2个主题。为了做到这一点,我定义了一些属性,如下所示: <attr format="color" name="item_background" />然后,我创建了两个主题,如下所示: <style name="ThemeA"> <item name="item_background">#123456</item> </style> <style name="ThemeB"> <item name="item_background">#ABCDEF</item> </style>这种方法效果很好,使我可以轻松创建和修改多个主题。问题在于,它似乎只能在Views中使用,而不能在Drawables中使用。例如,从布局内的View引用值可以工作: <TextView android:background="?item_background" />但是在Drawable中执行相同操作不会: <shape android:shape="rectangle"> <solid android:color="?item_background" /> </shape>运行应用程序时出现此错误: java.lang.UnsupportedOperationException: Can't convert to color: type=0x2如果不是?item_background我使用硬编码的颜色,而是可以使用,但是这不允许我使用主题。我也尝试过?attr:item_background,但同样发生。我该怎么办?为什么它在视图中起作用但在可绘制对象中不起作用?我在文档的任何地方都找不到此限制...
3 回答
![?](http://img1.sycdn.imooc.com/533e4bd900011a1d02000200-100-100.jpg)
慕运维8079593
TA贡献1876条经验 获得超5个赞
以我的经验,不可能在xml drawable中引用属性。
为了使您的主题,您需要:
每个主题创建一个xml可绘制对象。
使用@color标记或#RGB格式将所需的颜色直接包含在可绘制图形中。
在attrs.xml中为您的可绘制对象设置一个属性。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Attributes must be lowercase as we want to use them for drawables -->
<attr name="my_drawable" format="reference" />
</resources>
将您的可绘制对象添加到theme.xml中。
<style name="MyTheme" parent="@android:style/Theme.NoTitleBar">
<item name="my_drawable">@drawable/my_drawable</item>
</style>
使用属性在布局中引用您的可绘制对象。
<TextView android:background="?my_drawable" />
- 3 回答
- 0 关注
- 301 浏览
添加回答
举报
0/150
提交
取消