相关疑难解决方法(0)

如何从drawable引用样式属性?

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

 <attr format="color" name="item_background" />
Run Code Online (Sandbox Code Playgroud)

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

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

 <style name="ThemeB">
     <item name="item_background">#ABCDEF</item>
 </style>
Run Code Online (Sandbox Code Playgroud)

这种方法效果很好,允许我轻松地创建和修改几个主题.问题是它似乎只能在Views中使用,而不能在Drawables中使用.

例如,引用布局内View的值可以:

 <TextView android:background="?item_background" />
Run Code Online (Sandbox Code Playgroud)

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

 <shape android:shape="rectangle">
     <solid android:color="?item_background" />
 </shape>
Run Code Online (Sandbox Code Playgroud)

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

    java.lang.UnsupportedOperationException: Can't convert to color: type=0x2
Run Code Online (Sandbox Code Playgroud)

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

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

android android-theme android-drawable android-attributes

87
推荐指数
4
解决办法
3万
查看次数