tezvyn:

Theming in Compose: Style from a Single Source

AI-drafted, machine-checkedSource: developer.android.comintermediate
Theming in Compose: Style from a Single Source

Theming in Compose is like a CSS stylesheet for your app. You define colors, typography, and shapes once in a central `Theme` composable, and it cascades down. Use it for light/dark modes and brand consistency.

WHY IT EXISTS Theming exists to decouple an app's design from its component logic. Without a centralized system, hardcoding styles like colors and fonts in every component makes rebranding or adding features like dark mode incredibly tedious and error-prone. Theming provides a single source of truth for all visual attributes.

THE MENTAL MODEL Theming in Compose is like a set of CSS rules for your entire app, bundled into a Kotlin object. You wrap your entire UI in a Theme composable (e.g., YourAppTheme { ... }). Any composable inside that tree can then access the defined styles—colors, fonts, and shapes—from a central MaterialTheme object. It's a system of inheritance where styles cascade down from the top-level theme definition.

HOW IT WORKS At its core, Compose theming is built on three pillars: a ColorScheme for all colors (primary, secondary, background, etc.), Typography for font styles (headline, body, caption), and Shapes for component corner radiuses (small, medium, large). You define these three systems and pass them to your top-level MaterialTheme composable. Standard components like Button and Card automatically read from MaterialTheme to style themselves, for instance, using MaterialTheme.colorScheme.primary for a default button background.

WHEN TO USE IT Always. From the very beginning of a project, set up a basic theme. It is essential for implementing light and dark modes, supporting dynamic color from the user's wallpaper (Material You), providing custom styling for different form factors, or simply ensuring brand consistency.

WHEN NOT TO USE IT You almost never want to avoid it. Bypassing the theme for one-off styles should be a conscious and rare decision, as it creates technical debt. Even for a unique style, it's often better to extend the theme with a custom attribute rather than hardcoding a value directly in a component.

ONE CANONICAL EXAMPLE To apply the primary theme color to text, you don't hardcode a hex value. Instead, you reference the theme: Text("Hello", color = MaterialTheme.colorScheme.primary). When the user switches to dark mode, the ColorScheme provided to MaterialTheme changes, and this Text will automatically update to the correct primary color for the dark theme without any additional logic in the component itself.

Read the original → developer.android.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.