Home > Net >  Jetpack Compose: AndroidView Color in Dark Theme
Jetpack Compose: AndroidView Color in Dark Theme

Time:08-07

I found the colors of AndroidView in my app do not change with dark theme setting. For instance, I have a textView, whose textColor remains black(or grey) when system is in dark theme, causing the content hard to recognize. Of course I can set color for the textView like:

val textColor = if (isSystemInDarkTheme()) Color.White.toArgb() else Color.Black.toArgb()
...

    TextView(context).apply {
    ...
        setTextColor(textColor)
    ...
}

It works fine, but the question is that I get such textView in a few different screens, and I do not wish to repeat the same stuff like above in each of them. I've considered using CompositionLocal, but in that way I have to expose something like a LocalTextColor outside of the Composable functions to be imported by Composable functions in other packages and can't call isSystemInDarkTheme() to know how to set the correct value of it. Is there any better idea to solve this question than simply repeating the same code everywhere? Many thanks!

CodePudding user response:

Specify colors in your theme and retrieve the colors from there. This approach makes it possible to easily support dark theme and nested themes. You can retrieve the Colors provided to the MaterialTheme composable by using MaterialTheme.colors.

    private val Yellow200 = Color(0xffffeb46)
private val Blue200 = Color(0xff91a4fc)
// ...

private val DarkColors = darkColors(
    primary = Yellow200,
    secondary = Blue200,
    // ...
)
private val LightColors = lightColors(
    primary = Yellow500,
    primaryVariant = Yellow400,
    secondary = Blue700,
    // ...
)

MaterialTheme(
    colors = if (darkTheme) DarkColors else LightColors
) {
    // app content
}

and in composable:

Text(
    text = "Hello theming",
    color = MaterialTheme.colors.primary
)
  • Related