How to Use Theme in Compose in Android: Simple Guide
In Jetpack Compose, you use
MaterialTheme to apply a theme to your UI components. Wrap your composables inside MaterialTheme and customize colors, typography, and shapes by providing a theme object or using the default one.Syntax
The basic syntax to use a theme in Compose is to wrap your UI inside MaterialTheme. You can provide custom colors, typography, and shapes or use the default theme.
Example parts:
MaterialTheme(colors, typography, shapes) { ... }- applies the theme.colors- defines color palette.typography- defines font styles.shapes- defines corner shapes.- The content inside the lambda uses the theme.
kotlin
MaterialTheme(
colors = lightColors(),
typography = Typography(),
shapes = Shapes()
) {
// Your UI components here
}Example
This example shows how to use MaterialTheme to style a simple text with themed colors and typography.
kotlin
import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.sp @Composable fun ThemedText() { MaterialTheme( colors = lightColors(primary = Color(0xFF6200EE)), typography = Typography().copy( body1 = Typography().body1.copy(fontSize = 20.sp) ) ) { Text(text = "Hello Theme!", color = MaterialTheme.colors.primary, style = MaterialTheme.typography.body1) } } @Preview @Composable fun PreviewThemedText() { ThemedText() }
Output
A screen showing the text "Hello Theme!" in purple color with font size 20sp.
Common Pitfalls
Common mistakes when using themes in Compose include:
- Not wrapping your UI inside
MaterialTheme, so theme colors and typography are not applied. - Overriding colors or styles directly on components, which ignores the theme.
- Forgetting to use
MaterialTheme.colorsandMaterialTheme.typographyinside your composables.
kotlin
/* Wrong way: hardcoded color ignores theme */ Text(text = "Hello", color = Color.Red) /* Right way: use theme color */ Text(text = "Hello", color = MaterialTheme.colors.primary)
Quick Reference
Tips for using themes in Compose:
- Always wrap your UI in
MaterialThemeto apply consistent styling. - Use
MaterialTheme.colors,MaterialTheme.typography, andMaterialTheme.shapesinside your composables. - Customize themes by creating your own
Colors,Typography, andShapesobjects. - Use
darkColors()orlightColors()for quick color palettes.
Key Takeaways
Wrap your UI inside MaterialTheme to apply theme styles.
Use MaterialTheme.colors and typography inside composables for consistent design.
Customize colors, typography, and shapes by passing them to MaterialTheme.
Avoid hardcoding colors or fonts to keep your app theme consistent.
Use lightColors() and darkColors() for easy color palette setup.