Skip to content

Instantly share code, notes, and snippets.

@iwata-n
Created September 16, 2021 08:04
Show Gist options
  • Save iwata-n/c3300fbae9e906b8e5f5aa8eb426d72e to your computer and use it in GitHub Desktop.
Save iwata-n/c3300fbae9e906b8e5f5aa8eb426d72e to your computer and use it in GitHub Desktop.
独自の色を持ったテーマを作る

用意するテーマ

@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,
    )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment