用意するテーマ
@Stable
data class MyColors(
val actionBar: Color,
val primary: Color,
val secondary: Color,
val background: Color,
val surface: Color,
val error: Color,
val textColor: Color,
val textSecondaryColor: Color,
val textFieldColor: Color,
) {
fun toColors(isLight: Boolean): Colors = Colors(
primary = primary,
primaryVariant = primary,
secondary = secondary,
secondaryVariant = secondary,
background = background,
surface = surface,
error = error,
onPrimary = White,
onSecondary = White,
onBackground = textColor,
onSurface = textColor,
onError = primary,
isLight = isLight,
)
}
private val ColorPalette = MyColors(
actionBar = White,
primary = Blue,
secondary = Black,
background = White,
surface = White,
error = Red,
textColor = Black,
textSecondaryColor = Gray,
textFieldColor = LightGray,
)
@Composable
fun ProvideMyColors(
colors: MyColors,
content: @Composable () -> Unit
) {
val colorPalette = remember {
colors
}
CompositionLocalProvider(localMyColors provides colorPalette, content = content)
}
private val localMyColors = staticCompositionLocalOf<MyColors> {
error("error")
}
object MyTheme {
val colors: MyColors
@Composable
get() = localMyColors.current
}
@Composable
fun MyTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit) {
val colors = ColorPalette
ProvideMyColors(colors = colors) {
MaterialTheme(
colors = colors.toColors(darkTheme),
typography = Typography,
shapes = Shapes,
content = content
)
}
}
こんな感じで使える
@Composable
fun ErrorColorText() {
Text(
text = errorMessage,
color = MyTheme.colors.error,
style = Typography.caption,
)
}