gpt4 book ai didi

Android Theme drawable 不适用于 Color Drawable(错误?)

转载 作者:数据小太阳 更新时间:2023-10-29 02:35:07 25 4
gpt4 key购买 nike

所以我正在尝试制作一个使用基于主题的颜色作为背景的 selector。按照 this SO answer 的说明,我首先在 res/values/colors.xml 中定义我的颜色可绘制对象:

<color name="selected">#FFF7C9</color>

然后我在 res/values/attrs.xml 中定义一个属性:

<attr name="drawable_selected" format="reference" />

然后在我的主题中,我将属性设置为我的颜色可绘制对象 (res/values/styles.xml):

<style name="AppThemeWhite" parent="AppTheme">
<item name="drawable_selected">@color/selected</item>
</style>

最后,我在选择器 (res/drawable/selected_background) 中引用了该属性:

<selector>
<item android:state_activated="true" android:drawable="?drawable_selected" />
<item android:drawable="@android:color/transparent" />
</selector>

当我运行它时,我在尝试扩充使用选择器的类时收到错误 Binary XML file line #2: Error inflating class <unknown>。但是,当我更改选择器的 state_activated 以使用 android:drawable="@color/selected" 直接引用 drawable 时,它​​起作用了。

这是一个错误,还是我做错了什么?

编辑

如果我添加一个颜色属性(res/values/attrs.xml)

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

并在我的主题中定义颜色(res/values/styles.xml)

<item name="selected_color">#FFF7C9</item>

我可以根据它们更改可绘制的颜色 (res/values/colors.xml)

<color name="selected">?selected_color</color>

并在我的选择器中使用 android:drawable="@color/selected 直接引用可绘制对象。但是,这也会导致崩溃!并将可绘制颜色更改回 #FFF7C9 的硬编码值可以修复它。似乎整个主题系统都坏了......

最佳答案

原因

是的,从可绘制对象(或颜色)引用自定义主题属性目前在 Android 上不起作用。

在这里您可以看到有关很久以前报告的问题的更多详细信息:https://code.google.com/p/android/issues/detail?id=26251

正如您所看到的,他们最终在 Android L 版本中解决了这个问题,但是任何低于 L 的地方,这样的引用都会失败。

解决方案

要解决此问题,您需要执行以下操作:

<selector>
<item android:state_activated="true" android:drawable="@color/selected" />
<item android:drawable="@android:color/transparent" />
</selector>

其中 @color/selected 定义为您帖子的开头:

<color name="selected">#FFF7C9</color>

关于Android Theme drawable 不适用于 Color Drawable(错误?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25818344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com