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

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

问题描述

我想有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>

该方法的伟大工程,让我能够轻松创建和修改的几个主题。问题是,它似乎只能用在视图中,而不是可绘

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" />

但做同样的绘制对象不会:

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 我用硬codeD的颜色,它的工作原理,但是,这并不让我用我的主题。我也试过 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.

我怎么能这样做?为什么它在视图中而不是在可绘制工作?我找不到任何地方此限制<一个href="http://developer.android.com/guide/topics/resources/accessing-resources.html#ReferencesToThemeAttributes">the文档 ...

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绘制。
为了使你的主题,你需要:

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绘制。
  • 包括所需要的颜色分为直接与 @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 的做一个属性的绘制。

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>

添加您绘制到您的 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天全站免登陆