Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 104 ยท Building a Real UI

Material 3 and Theming

Learn Material 3 in Compose: MaterialTheme, color schemes and roles, dynamic color, typography, shapes, dark theme and how design tokens keep UI consistent.

Look at any polished Android app and you will notice that its buttons, cards, text and colors belong together, and that the whole app switches to a dark look when the system does. That consistency does not come from setting a color on every widget. It comes from a theme: one object that holds the app's colors, type styles and shapes, and that every component reads from.

Compose ships with Material 3 (also called Material You), Google's design system, as the androidx.compose.material3 library. This lesson explains how MaterialTheme works, what the color roles mean, how dynamic color and dark theme fit in, and why you should refer to tokens instead of hard-coded values. The Compose code is read-only because it needs the Android SDK. The TryIt blocks are Kotlin stand-ins: a small token resolver that picks light or dark values, and a contrast checker. They model the idea, not the Material library.

MaterialTheme: three token sets

MaterialTheme is a composable that makes three things available to everything inside it:

  • colorScheme: the colors, accessed as MaterialTheme.colorScheme.primary
  • typography: text styles, accessed as MaterialTheme.typography.bodyLarge
  • shapes: corner styles, accessed as MaterialTheme.shapes.medium

Almost every Material component reads these values by default. A Button uses colorScheme.primary for its background and colorScheme.onPrimary for its text, with no code from you. You define the theme once and wrap your content in it, usually in the activity's setContent (see Activities and setContent):

Kotlin
// read-only example: needs Compose and Material 3
@Composable
fun NotesTheme(
    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 -> DarkColors
        else -> LightColors
    }

    MaterialTheme(
        colorScheme = colorScheme,
        typography = AppTypography,
        shapes = AppShapes,
        content = content
    )
}

This is the shape of the theme file the Android Studio project wizard generates. Notice that the function takes content as a trailing lambda, a slot (Composable Functions). Anything inside the lambda, however deep, can read the theme.

Internally the theme values travel through CompositionLocals, which are implicit parameters that flow down the tree without being passed by hand. That is why MaterialTheme.colorScheme is a property on an object (MaterialTheme) and still returns the colors of the nearest enclosing theme. You can nest a second MaterialTheme around one part of the screen, for example a banner with an inverted look, and only that subtree changes.

Color roles

A Material 3 ColorScheme is not a bag of random colors. It is a set of roles, each with a meaning, arranged in pairs: a fill color and the color to use on top of it.

Role Used for
primary / onPrimary Main brand color: filled buttons, active states; and the text or icons on it
primaryContainer / onPrimaryContainer A softer fill for less prominent but still primary elements
secondary, tertiary (and their containers) Accents that add variety: chips, a second action, highlights
error / onError Errors and destructive actions
background / onBackground, surface / onSurface Screen and component backgrounds and the text on them
surfaceVariant, surfaceContainer* Layered surfaces such as cards and sheets
outline Borders and dividers

Two habits keep this system working:

  • Pick by role, not by appearance. For text on a card use onSurface; for a warning color use error. Do not write Color(0xFF6750A4) in a screen.
  • Always pair a fill with its on color. The pairs are designed to have enough contrast with each other. Text inside a Surface finds the right color automatically, because Surface sets LocalContentColor to the matching on color.
Kotlin
// read-only example: needs Compose and Material 3
Card(
    colors = CardDefaults.cardColors(
        containerColor = MaterialTheme.colorScheme.primaryContainer,
        contentColor = MaterialTheme.colorScheme.onPrimaryContainer
    )
) {
    Text("Hello", style = MaterialTheme.typography.titleMedium)
}

The first TryIt below is a stand-in for how a theme resolves roles. lightColors and darkColors are maps from role name to a color, Theme keeps a stack of active color sets (like nested MaterialTheme calls), and role() reads the innermost one. The numbers are the Material 3 baseline purple palette.

Kotlin A color-scheme token resolver for light and dark (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The same code reads the same role names in all three places and gets different values: that is what a design token buys you. Changing the brand color later means editing one map.

Dynamic color

On Android 12 (API 31) and later, the system can derive a palette from the user's wallpaper. Material 3 exposes it through dynamicLightColorScheme(context) and dynamicDarkColorScheme(context). An app that uses them takes on the user's colors, which is the "You" in Material You. Because these functions do not exist below API 31, the theme code checks Build.VERSION.SDK_INT and falls back to your own static schemes (LightColors and DarkColors above) on older devices, or when the user turns dynamic color off in your settings.

Dynamic color is a good default for utility apps. Apps with a strong brand identity usually keep their own colors for key surfaces and may turn dynamic color off. Either way, because you read roles and never hard-code colors, the screens work with both.

You generate a static scheme from one brand color with the Material Theme Builder tool (a web page and a Figma plugin) that exports Color.kt and Theme.kt. A scheme is built with lightColorScheme(primary = ..., onPrimary = ..., ...) and darkColorScheme(...); roles you do not set get defaults from the baseline palette.

Dark theme

isSystemInDarkTheme() returns whether the system is in dark mode and triggers recomposition when it changes. Pass it into your theme, as in the example above, and choose the dark scheme. Android recreates the activity on a theme change, so your saved state matters here (see Configuration Changes and Saved State).

Dark theme is not "invert all colors". Dark surfaces avoid pure black and use slightly lighter tones for raised elements, and accent colors become lighter and less saturated so that they are not harsh. The on colors flip as well: dark text on a light primary fill. You get this for free by using the generated dark scheme and the role names.

Typography and shapes

Typography has 15 named styles in five families: display, headline, title, body and label, each in large, medium and small (displayLarge, bodyMedium, labelSmall, and so on). Each is a TextStyle with font size, weight and line height. Components use them (a Button uses labelLarge) and you choose one by purpose, not by pixel size:

Kotlin
// read-only example: needs Compose and Material 3
val AppTypography = Typography(
    titleLarge = TextStyle(
        fontFamily = FontFamily.Default,
        fontWeight = FontWeight.SemiBold,
        fontSize = 22.sp,
        lineHeight = 28.sp
    ),
    bodyLarge = TextStyle(fontSize = 16.sp, lineHeight = 24.sp)
)

Text("Notes", style = MaterialTheme.typography.titleLarge)

Any style you do not pass keeps its default. Use sp for text so it follows the user's font-size setting; custom fonts are covered in Text, Images and Icons.

Shapes defines the corner roundness at five sizes: extraSmall, small, medium, large and extraLarge. Cards use medium, buttons use a fully rounded shape, dialogs use extraLarge:

Kotlin
// read-only example: needs Compose and Material 3
val AppShapes = Shapes(
    small = RoundedCornerShape(8.dp),
    medium = RoundedCornerShape(16.dp)
)

Checking contrast

Colors must stay readable, which means enough contrast between text and its background. The Web Content Accessibility Guidelines define contrast ratio from the relative luminance of the two colors: (lighter + 0.05) / (darker + 0.05). Normal body text should reach 4.5:1, large text and key icons 3:1. Material's paired roles are designed to meet this, but a custom brand color or a hand-picked pair may not.

The second stand-in computes that ratio for each pair in the two schemes. It is the standard formula, not Android code, and shows why the paired roles exist.

Kotlin Contrast of role pairs (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Run it and compare the standard pairs with the last line of the light scheme: a custom grey that looks fine on a bright monitor can fail badly. Check your own palette the same way, or with the accessibility scanner you will meet in Accessibility and Localization.

Practical advice

  • Create a theme composable once and wrap the whole app in it. Previews should wrap in it too, so they show real colors.
  • Read from MaterialTheme.colorScheme, typography and shapes; keep raw Color(...) values in Color.kt.
  • Add your own tokens (spacing values, extra semantic colors) with a CompositionLocal when Material's roles are not enough, rather than scattering constants.
  • Test both themes and, if you use dynamic color, at least two wallpapers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which three sets of design values does MaterialTheme provide?

    MaterialTheme exposes colorScheme, typography and shapes. Components read them automatically, and you read them with MaterialTheme.colorScheme, .typography and .shapes.
  2. 2. Why does Material 3 pair roles such as primary and onPrimary?

    A fill role and its on role are designed together for readable contrast, so text on a primary button uses onPrimary and text on a surface uses onSurface.
  3. 3. What must your theme do before calling dynamicLightColorScheme?

    Dynamic color needs API 31 or newer. The theme checks Build.VERSION.SDK_INT and falls back to its own LightColors or DarkColors.
  4. 4. What is the recommended minimum contrast ratio for normal body text?

    WCAG recommends 4.5:1 for normal text and 3:1 for large text. 21:1 is the maximum possible (black on white).

Summary

  • MaterialTheme provides colorScheme, typography and shapes to everything inside it; components read them automatically.
  • Color roles come in fill and on pairs; use roles by meaning and never hard-code colors in screens.
  • Dynamic color (API 31+) derives a scheme from the wallpaper; always keep a static fallback.
  • Use isSystemInDarkTheme() to choose between light and dark schemes; dark is a designed scheme, not inverted colors.
  • Typography has 15 named styles (use sp); shapes has five corner sizes.
  • Check contrast (4.5:1 for body text) when you use custom colors.
  • The Compose code is read-only; the TryIt blocks are stand-ins for token resolution and contrast checking.

Next: Buttons, Text Fields and Forms