Skip to content

Instantly share code, notes, and snippets.

@mirland
Created May 13, 2021 22:07
Show Gist options
  • Save mirland/7d4da7cfd9ec85dd9e63ce9759a5e59e to your computer and use it in GitHub Desktop.
Save mirland/7d4da7cfd9ec85dd9e63ce9759a5e59e to your computer and use it in GitHub Desktop.
Extending Material theme in Jetpack Compose - Blog Code
@Stable
data class AppColors(
val subtitleTextColor: Color,
val materialColors: Colors,
){
val primary: Color
get() = materialColors.primary
// Add other material colors properties
}
enum class AppColorPalette {
BLUE,
PINK,
}
// AppCustomColors is private because we shouldn't expose a color that is not in a theme
private object AppCustomColors {
val PINK_AMARANTH = Color(0xffe91e63)
val PINK_MAROON = Color(0xffc2185b)
val PINK_MAUVELOUS = Color(0xfff48fb0)
}
private val darkPinkColors = AppColors(
linkTextColor = AppCustomColors.PINK_AMARANTH,
materialColors = darkColors(
primary = AppCustomColors.PINK_MAUVELOUS,
primaryVariant = AppCustomColors.PINK_MAROON,
.... // Material Colors
)
// Define lightPinkColors, darkBlueColors, lightBlueColors the same way
@Composable
fun appColors(colorPalette: AppColorPalette, darkTheme: Boolean): AppColors =
when (colorPalette) {
AppColorPalette.BLUE -> if (darkTheme) darkBlueColors else lightBlueColors
AppColorPalette.PINK -> if (darkTheme) darkPinkColors else lightPinkColors
}
@Immutable
data class AppDims(
val textSizeSmall: TextUnit,
val textSizeMedium: TextUnit,
val textSizeRegular: TextUnit,
val listItemVerticalPadding: Dp,
val listItemHorizontalPadding: Dp,
)
@Composable
fun appDims() = if (LocalConfiguration.current.screenWidthDp < 300) {
smallDeviceAppDims
} else {
regularAppDims
}
private val regularAppDims = AppDims(
textSizeSmall = 12.sp,
textSizeMedium = 14.sp,
textSizeRegular = 16.sp,
listItemVerticalPadding = 27.dp,
listItemHorizontalPadding = 30.dp,
)
private val smallDeviceAppDims = AppDims(
textSizeSmall = 12.sp,
textSizeMedium = 13.sp,
textSizeRegular = 14.sp,
listItemVerticalPadding = 15.dp,
listItemHorizontalPadding = 14.dp,
)
object AppTheme {
val colors: AppColors
@Composable
@ReadOnlyComposable
get() = LocalAppColors.current
}
private val LocalAppColors = staticCompositionLocalOf {
defaultAppColors() // For instance, pink dark colors
}
@Composable
fun AppTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
colorPalette: AppColorPalette = AppColorPalette.PINK,
content: @Composable () -> Unit,
) {
val colors = appColors(colorPalette = colorPalette, darkTheme = darkTheme)
CompositionLocalProvider(
LocalAppColors provides colors,
) {
MaterialTheme(
colors = colors.materialColors,
content = content,
)
}
}
@get:Composable
val Colors.subtitleTextColor: Color
get() = if (isLight) Red300 else Red700
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment