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

Android Kotlin中如何引用主题内的colorOnPrimary颜色?

问题:如何在代码中引用主题里的colorOnPrimary颜色

我在Android Studio 2021.2.1中用Kotlin开发,现有themes.xml文件如下:

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.ChordTrainer" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">#888888</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">#FFFFFF</item>
...
</resources>

目前我可以通过以下代码引用colorPrimary并绘制填充矩形:

fun drawRect(iv:ImageView) {
    val bitmap = Bitmap.createBitmap(iv.width, iv.height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)

    val paint = Paint()
    paint.style = Paint.Style.FILL
    paint.strokeWidth = 1f

    val typedValue = TypedValue()
    context.theme.resolveAttribute(android.R.attr.colorPrimary, typedValue, true)
    paint.color = typedValue.data
    canvas.drawRect(0f, 0f, 20f, 20f, paint)
    iv.setImageBitmap(bitmap)
}

但我想以类似方式引用主题中的colorOnPrimary颜色时,发现android.R.attr.colorOnPrimary这个资源ID不存在,请问该怎么实现?


解决方案

colorOnPrimary是Material Components库提供的主题属性,不属于Android框架原生的android.R.attr范畴,你可以通过以下两种方式实现引用:

方法一:直接使用Material库的属性ID

修改resolveAttribute的参数为Material库的属性ID即可,这是最直接的方式:

fun drawRect(iv:ImageView) {
    val bitmap = Bitmap.createBitmap(iv.width, iv.height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)

    val paint = Paint()
    paint.style = Paint.Style.FILL
    paint.strokeWidth = 1f

    // 引用colorOnPrimary属性
    val typedValue = TypedValue()
    context.theme.resolveAttribute(com.google.android.material.R.attr.colorOnPrimary, typedValue, true)
    paint.color = typedValue.data
    
    canvas.drawRect(0f, 0f, 20f, 20f, paint)
    iv.setImageBitmap(bitmap)
}

方法二:自定义属性映射(可选)

如果不想直接依赖Material库的包名,可通过自定义属性实现映射:

  1. 在res/values/attrs.xml中添加自定义属性:
<resources>
    <attr name="colorOnPrimary" format="color" />
</resources>
  1. 确保themes.xml中已配置该属性(你当前的配置已满足):
<item name="colorOnPrimary">#FFFFFF</item>
  1. 代码中引用自定义属性:
context.theme.resolveAttribute(R.attr.colorOnPrimary, typedValue, true)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 09:15:31