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

如何在代码中通过Styles.xml属性名设置控件颜色(无需判断主题)

在代码中通过主题属性名直接获取对应颜色(Xamarin.Android/Android通用)

当然可以!你已经在主题里定义了这些颜色属性,不管是Xamarin.Android还是原生Android,都能直接通过主题属性名获取对应颜色,完全不用手动判断当前是浅色还是深色主题,和你在XML里的用法逻辑完全一致。

第一步:确保自定义属性已声明(关键前提)

虽然你已经在Styles.xml里使用了这些属性,但需要先在res/values/attrs.xml中声明这些自定义属性,让系统能够识别它们:

<resources>
    <attr name="colour_text" format="color" />
    <attr name="colour_text_subtle" format="color" />
    <attr name="colour_text_more_subtle" format="color" />
</resources>

Xamarin.Android 实现方式

你可以通过TypedArray来获取当前主题中对应属性的颜色值,示例代码如下:

直接使用的示例

// 在Activity或Context环境中
using (var typedArray = this.ObtainStyledAttributes(new int[] { Resource.Attribute.colour_text_subtle }))
{
    // 获取颜色值,第二个参数是属性未定义时的默认颜色
    int subtleTextColor = typedArray.GetColor(0, Android.Graphics.Color.Gray);
    // 给TextView设置文本颜色
    yourTextView.SetTextColor(subtleTextColor);
    // 务必回收TypedArray,避免内存泄漏
    typedArray.Recycle();
}

封装成工具方法(推荐复用)

如果多个地方需要使用,可以封装成一个工具类方法,减少重复代码:

public static class ThemeUtils
{
    public static int GetThemeColor(Context context, int attributeId, int defaultColor)
    {
        using (var typedArray = context.ObtainStyledAttributes(new int[] { attributeId }))
        {
            int color = typedArray.GetColor(0, defaultColor);
            typedArray.Recycle();
            return color;
        }
    }
}

// 使用示例
int subtleColor = ThemeUtils.GetThemeColor(this, Resource.Attribute.colour_text_subtle, Android.Graphics.Color.Gray);
yourTextView.SetTextColor(subtleColor);

原生Android(Java/Kotlin)通用指导

如果你需要参考原生的实现方式,这里也提供对应的代码:

Java 版本

// 在Activity或Fragment中
TypedArray typedArray = getContext().obtainStyledAttributes(new int[]{R.attr.colour_text_subtle});
int subtleTextColor = typedArray.getColor(0, Color.GRAY);
yourTextView.setTextColor(subtleTextColor);
// 必须回收TypedArray
typedArray.recycle();

Kotlin 版本(更简洁)

Kotlin的use函数可以自动帮你回收TypedArray,不用手动调用recycle():

val subtleTextColor = context.theme.obtainStyledAttributes(
    intArrayOf(R.attr.colour_text_subtle)
).use { it.getColor(0, Color.GRAY) }
yourTextView.setTextColor(subtleTextColor)

额外补充:和XML用法的呼应

其实你在XML里已经可以直接通过?attr/colour_text_subtle来设置控件属性,比如:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="?attr/colour_text_subtle" />

代码中的方式和XML的逻辑完全统一,系统会自动根据当前激活的主题(LightTheme或DarkTheme)返回对应的颜色值,全程不需要你手动判断主题类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:13:24