Compose提供了基于Material颜色规范的ColorPalette
,用于生成应用程序主题。它提供了lightColorPalette
和darkColorPalette
,用于分别定义浅色和深色模式的主题。
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)
)
}
}
如果您想为主题添加更多自定义颜色,可以使用ColorPalette
和扩展变量,如下所示:
@Composable
val ColorPalette.myColor: Color
get() = if(!isLight) Color(0xFF424242) else Color.White
现在你可以使用
MaterialTheme.colors.myColor
来包含颜色。
如果您想要从Android颜色XML中包含颜色,可以使用
colorResource(id = R.color.anyName)
函数。