简体   繁体   English

Jetpack Compose:深色主题中的 AndroidView 颜色

[英]Jetpack Compose: AndroidView Color in Dark Theme

I found the colors of AndroidView in my app do not change with dark theme setting.我发现我的应用程序中AndroidView的 colors 不会随着深色主题设置而改变。 For instance, I have a textView, whose textColor remains black(or grey) when system is in dark theme, causing the content hard to recognize.例如,我有一个 textView,当系统处于深色主题时,其 textColor 保持黑色(或灰色),导致内容难以识别。 Of course I can set color for the textView like:当然,我可以为 textView 设置颜色,例如:

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.它工作正常,但问题是我在几个不同的屏幕上得到了这样的 textView,我不想在每个屏幕上重复上面的相同内容。 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.我考虑过使用CompositionLocal ,但是这样我必须在 Composable 函数之外公开类似LocalTextColor的东西,以便由其他包中的 Composable 函数导入,并且不能调用isSystemInDarkTheme()来知道如何设置正确的值它。 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.在您的主题中指定 colors 并从那里检索 colors。 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 .您可以使用MaterialTheme.colors检索提供给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
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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