简体   繁体   中英

Jetpack Compose: AndroidView Color in Dark Theme

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!

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM