You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何R.attr.colorPrimary无法从本地项目R类解析?

问题原因与解决办法

核心原因

colorPrimary并非你本地项目定义的属性,而是AndroidX AppCompat/Material Components库提供的主题属性。本地项目的com.example.project.R类仅包含你在res/目录下主动声明的自定义资源(比如自定义属性、自定义颜色、布局文件等),不会自动包含依赖库中定义的属性。

为什么XML里能正常使用?

XML布局中使用?attr/colorPrimary时,Android的资源解析引擎会自动遍历当前Activity主题的继承链(你的Theme.Example继承自Theme.MaterialComponents.DayNight.DarkActionBar,而这个父主题又继承自Material库的基础主题),沿着链路找到该属性的定义,因此不需要显式指定属性的所属R类。

代码中的正确用法

在Kotlin/Java代码中,必须明确引用属性的所属R类:

  • 若使用Material Components库,直接引用com.google.android.material.R.attr.colorPrimary
  • 也可使用AppCompat库的androidx.appcompat.R.attr.colorPrimary

示例代码:

val typedValue = TypedValue()
view.context.theme.resolveAttribute(com.google.android.material.R.attr.colorPrimary, typedValue, true)
val colorPrimary = typedValue.data

补充说明

如果确实需要在本地项目中自定义同名属性,可以在res/values/attrs.xml中声明:

<resources>
    <attr name="colorPrimary" format="color" />
</resources>

此时本地R.attr.colorPrimary就能被识别,但这种做法完全没必要——因为你已经在主题中复用了库定义的colorPrimary,直接引用库的R类更简洁。

内容的提问来源于stack exchange,提问作者phazei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 11:47:24