Search code examples
kotlinthemes

How can I reference theme colors in Kotlin


Working in Kotlin on Android Studio 2021.2.1, for a themes.xml file like this:

<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>
...

In class code, I can reference the colorPrimary color and use it to do something like draw a filled rectangle like this:

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)
}

I'd like to be able to similarly reference the colorOnPrimary color from themes.xml, but the android.R.attr.colorOnPrimary resource ID doesn't exist. Any ideas on how I could reference it?


Solution

  • I think it's better to use the most obvious way for this, you can just move the colorOnPrimary to colors.xml

    <color name="colorOnPrimary">#FFFFFF</color>
    

    Then you can use the color reference in the themes.xml

    <item name="colorOnPrimary">@color/colorOnPrimary</item>
    

    And in the code

    paint.color = context.getColor(R.color.colorOnPrimary)