如何从可绘制对象引用样式属性? [英] How to reference style attributes from a drawable?

查看:35
本文介绍了如何从可绘制对象引用样式属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的应用程序提供 2 个可选主题.为了做到这一点,我定义了一些属性,如下所示:

I want to have 2 selectable themes for my application. In order to do that, I defined some attributes, like this:

 <attr format="color" name="item_background" />

然后,我创建了两个主题,如下所示:

Then, I created both themes, like this:

  <style name="ThemeA">
     <item name="item_background">#123456</item>
 </style>

 <style name="ThemeB">
     <item name="item_background">#ABCDEF</item>
 </style>

这种方法效果很好,让我可以轻松创建和修改多个主题.问题是似乎只能在Views中使用,而不能在Drawables中使用.

This method works great, allowing me to create and modify several themes easily. The problem is that it seems that it can be used only in Views, and not in Drawables.

例如,从布局内的视图中引用值有效:

For example, referencing a value from a View inside a layout works:

 <TextView android:background="?item_background" />

但是在 Drawable 中做同样的事情不会:

But doing the same in a Drawable doesn't:

 <shape android:shape="rectangle">
     <solid android:color="?item_background" />
 </shape>

运行应用程序时出现此错误:

I get this error when running the application:

    java.lang.UnsupportedOperationException: Can't convert to color: type=0x2

如果我使用硬编码颜色而不是 ?item_background,它可以工作,但这不允许我使用我的主题.我也试过 ?attr:item_background,但同样发生.

If instead of ?item_background I use a hardcoded color, it works, but that doesn't allow me to use my themes. I also tried ?attr:item_background, but the same happens.

我怎么能这样做?为什么它在 Views 中有效,而在 Drawables 中无效?我在文档的任何地方都找不到这个限制...

How could I do this? And why does it work in Views but not in Drawables? I can't find this limitation anywhere in the documentation...

推荐答案

根据我的经验,不可能在 XML drawable 中引用属性.
为了制作您的主题,您需要:

In my experience it is not possible to reference an attribute in an XML drawable.
In order to make your theme you need to:

  • 为每个主题创建一个 XML drawable.
  • 使用 @color 标签或 #RGB 格式将所需颜色直接包含到可绘制对象中.

  • Create one XML drawable per theme.
  • Include the needed color into you drawable directly with the @color tag or #RGB format.

attrs.xml 中为你的 drawable 创建一个属性.

Make an attribute for your drawable in 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>

将您的 drawable 添加到您的 theme.xml.

Add your drawable to your theme.xml.

<style name="MyTheme" parent="@android:style/Theme.NoTitleBar">
   <item name="my_drawable">@drawable/my_drawable</item>
</style>

使用您的属性在布局中引用您的可绘制对象.

Reference your drawable in your layout using your attribute.

<TextView android:background="?my_drawable" />

这篇关于如何从可绘制对象引用样式属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆