gpt4 book ai didi

Android 颜色选择器不适用于自定义属性

转载 作者:IT老高 更新时间:2023-10-28 23:33:09 25 4
gpt4 key购买 nike

我有 attrs.xml

<resources> 
<!-- theme specific colors -->
<attr format="reference|color" name="foreground" />
<attr format="reference|color" name="background" />
</resources>

然后在theme.xml中

<style name="MyTheme" parent="android:Theme.Black">
<item name="android:windowNoTitle">true</item>
<item name="foreground">#0000FF</item>
<item name="background">#00FF00</item>
</style>

我还创建了名为 forground_to_background.xml 的颜色选择器

<selector xmlns:android="http://schemas.android.com/apk/res/android">   
<item android:state_pressed="true" android:color="?background"/> <!-- pressed -->
<item android:state_focused="true" android:color="?background"/> <!-- focused -->
<item android:color="?foreground"/> <!-- default -->
</selector>

现在我想在 TextView 中一起使用它:

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/forground_to_background" />

不幸的是,它不起作用。我只有一种颜色——红色,而不是漂亮的绿蓝色。 TextView 总是红色的。当我将 TextView 更改为使用“?foreground”时,颜色会发生变化。此外,当我将颜色选择器从“?xxxx”更改为硬编码值时,“#00f”颜色开始起作用。

问题出在哪里?我做错了什么?

编辑:我相信这是问题/错误 Can a selector resource use a color defined in a style? 的重复

编辑2:此外,当我尝试在 ListView 应用程序崩溃中使用此 TextView 时。它无法解析 XML。

最佳答案

为选择器选择颜色时,您不能引用 ?attr/。如果您想在选择器中使用每个主题的颜色,您可以做的是创建多个引用 @color/和 @drawable/的选择器,然后有一个“引用”属性,它将其中一个选择器与给定的样式相关联。

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

然后你必须像这样设置文本颜色

android:textColor="?attr/forground_to_background"

我相信文本总是红色的,因为 Android 将 attr 的整数值解释为颜色(红色),而不是使用它来查找您实际想要的内容。

关于Android 颜色选择器不适用于自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9005015/

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