Search code examples
android-jetpack-composeandroid-jetpackandroid-compose-textfield

How to get Color(JetpackCompose) from resources correctly?


I need to use resources in order to support different BuildVars, so I have Color.kt file where I define my colors, the problem is that if I get a color from the resources colors.xml like this

val MyWhiteColor: Color = Color(R.color.my_white_color)

and use it like this

    Text(
        text = ...,
        style = TextStyle(
            color = MyWhiteColor
        )
    )

I get blue color instead of white, however, if I change the implementation to

val MyWhiteColor: Color = Color(android.graphics.Color.parseColor("#FFFFFF"))

it works as expected and I get white color.

What am I missing? Why when I get the value from colors.xml the color converts to blue?


Solution

  • You can't load from an XML resource file outside of a Composable because Compose needs a context and it also has to react to configuration changes.

    You can either just define your colors in Color.kt without XML color resources or you can load from a resource in a composable using:

    colorResource(R.color.my_white_color)