Resources$NotFoundException 将属性作为颜色访问时

Resources$NotFoundException when accessing an attribute as a color

所以我将颜色定义为属性,因为它取决于主题。

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

在主题中定义为

<style name="BaseReferencesTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="primary_text_color">#ffffffff</item>
</style>

我想用真实的颜色资源包装它。

<color name="selected_color_normal">?attr/primary_text_color</color>

然后从代码中读取

int resolvedColor = ContextCompat.getColor(context, R.color.selected_color_normal);

当我这样做时,出现异常

 android.content.res.Resources$NotFoundException: Resource ID #0x7f06010e type #0x2 is not valid
        at android.content.res.Resources.getColor(Resources.java:955)
        at android.content.Context.getColor(Context.java:588)
        at android.support.v4.content.ContextCompat.getColor(ContextCompat.java:523)

我在这里使用了几个模块:

  1. attr_module 定义属性的地方。
  2. theme_module 定义主题并设置到应用程序的地方
  3. usage_module 对主题一无所知,但确实依赖于 attr_module.

我确定该主题已应用于 usage_module 中的视图。当我不尝试以编程方式读取 selected_color_normal,而只是应用属性时,所有依赖项都已正确设置 - 一切正常。

感谢您的帮助!

NotFoundException - Resource ID #0x7f06010e type #0x2 is not valid

#ffffffff

?attr/primary_text_color

可能会导致问题。因为你得到 NotFoundException 这意味着它找不到特定的颜色,它只接受 <color.

中的 指定的颜色

我想,这里的问题是因为primary_text_color是属性,而selected_color_normal是颜色。

努力做到

<color name="selected_color_normal">#FFFFFFFF</color>

然后,如果需要,您可以根据自己的风格给出 primary_text_colorselected_color_normal

<style name="BaseReferencesTheme" parent="Theme.AppCompat.NoActionBar">
<item name="primary_text_color">@color/selected_color_normal</item>

目前我认为这个问题无法解决。目前我的方法是尽可能使用 ?attr/primary_text_colorR.attr.primary_text_color

我认为您不能从 values/colors 引用自定义属性,就像您提到的这一行。由于编译时间与运行时间的差异。

<color name="selected_color_normal">?attr/primary_text_color</color>`

现在,您可以通过使用“引用”标志定义属性来从代码中引用属性

<attr name="primary_text_color" format="color|reference"/>