Skip to content

Instantly share code, notes, and snippets.

@Bradleycorn
Last active November 26, 2021 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Bradleycorn/4929f7d0d5e7b6c091c77d176a35c765 to your computer and use it in GitHub Desktop.
Save Bradleycorn/4929f7d0d5e7b6c091c77d176a35c765 to your computer and use it in GitHub Desktop.
An Example Theme for Jetpack Compose that uses the built-in Material Theme, but adds a single extra color, "Tertiary".
package net.bradball.android.androidapptemplate.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
private val DarkColorPalette = AppColors(
materialColors = darkColors(
primary = purple200,
primaryVariant = purple700,
secondary = teal200),
tertiary = Color.Black,
onTertiary = Color.White
)
private val LightColorPalette = AppColors(
lightColors(
primary = purple500,
primaryVariant = purple700,
secondary = teal200
),
tertiary = Color.Blue,
onTertiary = Color.Black
)
@Composable
fun MyApplicationTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit) {
val colors: AppColors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
ProvideAppColors(colors = colors) {
MaterialTheme(
colors = colors.materialColors,
typography = typography,
shapes = shapes) {
content()
}
}
}
object MyApplicationTheme {
@Composable
val colors: AppColors
get() = AmbientAppColors.current
}
class AppColors(
materialColors: Colors,
tertiary: Color,
onTertiary: Color
) {
var tertiary by mutableStateOf(tertiary)
private set
var onTertiary by mutableStateOf(onTertiary)
private set
// I wish the material [Colors] class would expose it's `updateFrom()`
// method. I think this would not be necessary if it did, or if it
// provided some way to be able to update it's colors. But I (kindof)
// understand why they don't.
var materialColors by mutableStateOf(materialColors)
private set
fun update(otherColors: AppColors) {
materialColors = otherColors.materialColors
tertiary = otherColors.tertiary
onTertiary = otherColors.tertiary
}
}
@Composable fun ProvideAppColors(colors: AppColors, content: @Composable () -> Unit) {
val colorPalette = remember { colors }
colorPalette.update(colors)
Providers(AmbientAppColors provides colorPalette, children = content)
}
internal val AmbientAppColors = staticAmbientOf{ LightColorPalette }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment