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

Android如何通过attr.xml设置颜色?调用R.attr.myColor不生效怎么解决?

问题原因

  • setTextColor() 方法要求传入实际颜色整数值,你直接传入的R.attr.myColor是自定义属性的资源ID,是系统给该属性分配的唯一标识数值,不是你配置的色值,直接传递会被错误解析,无法得到预期效果。
  • 自定义属性名和主题中配置的属性名不匹配:你在attr.xml中声明的属性名为myColor,但在themes.xml和themes-night.xml中配置的item名为textMessageColor,二者完全不对应,系统无法将属性和你配置的颜色关联。

解决方法

1. 修正主题配置的属性名

将两个主题配置文件中的item名和你自定义的属性名对齐:
themes.xml修改为:

<item name="myColor">@color/black</item>

themes-night.xml修改为:

<item name="myColor">@color/white</item>

2. 代码中正确读取主题属性对应的颜色

需要先从当前上下文的主题中解析出属性对应的实际色值,再设置给TextView,示例代码如下:

Kotlin 示例

// 从主题中获取自定义属性对应的色值
val typedArray = context.theme.obtainStyledAttributes(intArrayOf(R.attr.myColor))
val targetColor = typedArray.getColor(0, Color.BLACK) // 第二个参数为获取失败的默认色值,可自行调整
typedArray.recycle() // 必须调用回收TypedArray,避免内存泄漏
textView.setTextColor(targetColor)

Java 示例

TypedArray typedArray = getContext().getTheme().obtainStyledAttributes(new int[]{R.attr.myColor});
int targetColor = typedArray.getColor(0, Color.BLACK);
typedArray.recycle();
textView.setTextColor(targetColor);

可选简化方案

如果是在XML布局中设置TextView颜色,不需要代码解析,直接引用属性即可自动适配主题:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="?attr/myColor"
    android:text="测试文本"/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:18:03