Review Jetpack compose codes - theme
To set Theme
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Composable
fun BasicCodelabTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context)
else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
(view.context as Activity).window.statusBarColor = colorScheme.primary.toArgb()
ViewCompat.getWindowInsetsController(view)?.isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
- DarkColorScheme and LightColorScheme define color schemes for dark and light themes respectively.
- The BasicCodelabTheme function sets the application’s theme, taking
darkTheme
anddynamicColor
parameters. - SideEffect is used to set the status bar color of the activity when the view is not in edit mode, and adjust the system status bar theme.
- MaterialTheme wraps actual UI content, applying the configured color scheme and typography.
1
2
3
4
5
6
7
8
9
10
11
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
BasicCodelabTheme {
MyApp(modifier = Modifier.fillMaxSize())
}
}
}
}
To wrap the BasicCodelabTheme
and specify a default theme
This post is licensed under CC BY 4.0 by the author.