简体   繁体   English

如何在 Jetpack Compose 中引用主题属性?

[英]How to reference theme attributes in Jetpack Compose?

So in the current andriod development, if we need to reference to a color set in the theme, we could simply do: (in layout xml)所以在目前的andriod开发中,如果我们需要在主题中引用一个颜色集,我们可以简单地这样做:(在layout xml中)

....
    <TextView
        ...
        android:textColor="?attr/colorPrimary"
        .../>
....

If I set a color blue in the theme.如果我在主题中设置蓝色。 I will get that color in the textview above.我会在上面的 textview 中得到那个颜色。

I was wondering how I could do the same in Jetpack Compose .我想知道如何在Jetpack Compose中做同样的事情。 In Compose , we do,Compose中,我们这样做,

MaterialTheme(...) {
    Column {
        Text(
            ...
            textStyle = TextStyle(color = ????) // How to I reference to the theme?
        )
    }
}

You can use something like:你可以使用类似的东西:

Text(text = "....",
     style = TextStyle(color = MaterialTheme.colors.primary))

Compose provide ColorPalette based on Material color specification to generate you app theme. Compose 提供基于 Material 颜色规范的ColorPalette来生成您的应用主题。 It provide lightColorPalette and darkColorPalette for defining theme for light and dark mode respectively.它提供lightColorPalettedarkColorPalette用于定义明暗模式的主题。

val lightThemeColors = lightColorPalette(
    primary = Color(0xFFFFFFFF),
    primaryVariant = Color(0xFFFFFFFF),
    onPrimary = Color.Black,
    secondary = Color.Transparent,
    onSecondary = Color.White,
    background = Color.White,
    onBackground = Color(0xFF212121),
    surface = Color.White,
    onSurface = Color(0xFF212121),
    error = Color.Red,
    onError = Color.White
)
val darkThemeColors = darkColorPalette(
    primary = Color(0xFF000000),
    primaryVariant = Color(0xFF000000),
    onPrimary = Color.White,
    secondary = Color.White,
    onSecondary = Color.White,
    surface = Color(0xFF212121),
    background = Color(0xFF212121),
    onBackground = Color.White,
    onSurface = Color.White,
    error = Color.Red,
    onError = Color.White
)
MaterialTheme(
colors = if(isSystemInDarkTheme()) darkThemeColors else lightThemeColors
) {
    Column {
        Text(
        textStyle = TextStyle(color = MaterialTheme.colors.primary)
        )
    }
}

If you want to add more custom color to you theme you can use ColorPalette with extension variable like shown below如果您想为您的主题添加更多自定义颜色,您可以使用带有扩展变量的ColorPalette ,如下所示

@Composable
val ColorPalette.myColor: Color
    get() = if(!isLight) Color(0xFF424242) else Color.White

Now you can use MaterialTheme.colors.myColor to include.现在您可以使用MaterialTheme.colors.myColor来包含。

If you want to include color from android colors xml you can do that using colorResource(id = R.color.anyName) function. If you want to include color from android colors xml you can do that using colorResource(id = R.color.anyName) function.

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

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