In Android Studio, how does a Compose @Preview render without a device, and why does previewing a screen that creates a ViewModel fail?
answer
- no emulator starts
- a ported Android framework
- what the renderer cannot construct
- preview the stateless half
basics
~20 sAndroid Studio renders @Preview composables in the editor with Layoutlib, an Android framework that runs off-device. It has no network or file access and cannot construct a ViewModel's dependencies, so preview a stateless composable that takes plain parameters.
solid answer
~50 sPutting `@Preview` on a composable tells Android Studio to render it in the file's design view. The IDE runs the preview code itself with `Layoutlib`, a ported Android framework that runs outside a device, so no emulator starts. That makes previews fast, but they have no network access and no file access, and some `Context` APIs are not fully available. A screen that creates its `ViewModel` fails to render: the preview system cannot construct the `ViewModel`'s parameters, such as repositories or use cases, and cannot build a dependency-injection graph such as Hilt's. The fix is in how the screen is split: a thin composable obtains the `ViewModel` and passes plain values to a stateless composable, and you preview the stateless one with sample data. Inside a preview, `LocalInspectionMode.current` is `true`, which lets you show a placeholder instead of real data.
code
kotlin · 19 lines@Composable
fun ProfileScreen(name: String, onEdit: () -> Unit) {
Column {
Text("Hello $name!")
Button(onClick = onEdit) { Text("Edit") }
}
}
class NamePreviewParameterProvider : PreviewParameterProvider<String> {
override val values = sequenceOf("Elise", "Frank", "Julia")
}
@Preview(showBackground = true)
@Composable
fun ProfileScreenPreview(
@PreviewParameter(NamePreviewParameterProvider::class) name: String
) {
MaterialTheme { ProfileScreen(name = name, onEdit = {}) }
}go deeper
Recall what @Preview is for and how it renders: Layoutlib, inside the IDE, with no device, no network and no files. Know the ViewModel limitation and its fix.
Explain the preview parameters, multipreview annotations and PreviewParameterProvider, and why combining annotations renders each one's variants rather than a matrix.
Show how preview-friendly screens shape the codebase: stateless composables, LocalInspectionMode guards for side effects, and shared multipreview annotations instead of copied preview functions.
Weigh how much a team should invest in preview coverage, such as shared multipreview sets for themes and font scales, against keeping previews cheap to render and maintain.
## What @Preview does A **composable** is a Kotlin function annotated with `@Composable` that emits UI. Adding **`@Preview`** to a composable tells Android Studio to show it in the **design view** of that file, next to the code, and to refresh it as you edit. The point is to avoid starting an emulator for every small visual change and keep the device for final look-and-feel checks. ## How a preview renders: Layoutlib Android Studio executes the preview code directly in the preview area using **`Layoutlib`**, a custom version of the Android framework built to run outside Android devices. It aims to render very close to what a device shows, but it is not a device, and that sets the limits: - **No network access**: a preview cannot load real data from a server. - **No file access**. - **Some `Context` APIs may not be fully available.** - **No `ViewModel` construction**: the preview system cannot build a `ViewModel`'s constructor parameters, and when the `ViewModel` comes from dependency injection it cannot build that graph either. Android Studio shows a rendering error for that composable. When a composable must behave differently in a preview, read **`LocalInspectionMode.current`**. It is `true` inside a preview, so you can show a placeholder image or sample text instead of making a real call. ## Fixing the ViewModel case The fix changes the code's shape. Passing `ViewModel` instances down to other composables couples them to the `ViewModel` type, which makes them harder to reuse, harder to test and impossible to preview. Instead: 1. Keep a thin **route** composable that obtains the `ViewModel` and reads its state. 2. Have it call a **stateless** composable that takes plain values and event lambdas. 3. Preview the stateless composable with sample data. How to hoist state well is a subject of the Jetpack Compose lessons. What belongs to Android Studio is that this split is the reliable way to give the preview something it can render. ## Common preview failures and their fixes - **A rendering error on a screen-level composable**: it creates a `ViewModel`. Preview the stateless composable underneath instead. - **A blank or broken area where real content should be**: the composable tries to load from the network or a file. Guard the call with `LocalInspectionMode.current` and show a placeholder in the preview. - **A preview that looks right in the IDE but not in Run Preview**: the deployed version ignores the annotation's arguments, so a `locale` or `widthDp` you set is not applied there. - **A red underline on `device`**: the value is invalid. The editor offers a fix (Alt + Enter, Replace with...) that is closest to what you typed. ## Configuring a preview `@Preview` takes parameters. Ctrl/⌘-click the annotation to see the full list. | Parameter | What it changes | |---|---| | `widthDp`, `heightDp` | fixed size in dp (by default the size wraps the content) | | `showBackground`, `backgroundColor` | background; `backgroundColor` is an ARGB `Long` such as `0xFF00FF00`, not a `Color` | | `locale` | the locale, e.g. `"fr-rFR"` | | `uiMode` | a `Configuration.UI_*` constant, such as night mode | | `fontScale` | font scaling | | `device` | a device ID such as `"id:pixel_4"` or a `spec:` string | | `showSystemUi` | draws the status and action bars | | `wallpaper` | a wallpaper for dynamic colour (needs Compose 1.4.0 or higher) | ## Many previews, little code - **Repeat `@Preview`** on one function to render it with different parameters. - **Multipreview annotations**: an `annotation class` that itself carries several `@Preview` annotations. Put it on any preview function and all its variants render. - **Templates**: `androidx.compose.ui:ui-tooling-preview` 1.6.0-alpha01 and later ship `@PreviewScreenSizes`, `@PreviewFontScales`, `@PreviewLightDark` and `@PreviewDynamicColors`. - **Combining** multipreview and plain `@Preview` annotations does **not** produce every combination: each annotation renders only its own variants. - **`@PreviewParameter`** with a **`PreviewParameterProvider`** feeds sample data. The provider's `values` sequence renders one preview per element, `limit` caps how many render, and overriding `getDisplayName()` replaces the default names (`user 0`, `user 1`, ...) with readable labels. ## Working with a rendered preview - **Focus mode** renders one preview at a time and saves resources. Grid and List modes show every variant at once. - **Interactive mode** lets you click and type in a sandboxed preview, which is useful for checking states and animations. - **Run Preview** deploys that one preview to a device or emulator as a new `Activity` inside your app, sharing its context and permissions. Arguments such as `widthDp` and `locale` are **not** applied to the deployed version. - Hovering shows composable outlines, and clicking one jumps to its code.
- How do you preview one composable in light and dark theme and at several font scales without copying the preview function?Use multipreview. Either declare an `annotation class` that carries several `@Preview` annotations with different `fontScale` or `uiMode` values, or use the templates in `ui-tooling-preview` 1.6.0-alpha01+, such as `@PreviewLightDark` and `@PreviewFontScales`. Stacking two of them renders each annotation's own variants, not every combination.
- What changes when you click Run Preview on a preview?Android Studio deploys that preview to the connected device or emulator as a new `Activity` in your app, so it shares the app's context and any permissions already granted. The arguments on the `@Preview` annotation, such as `widthDp` or `locale`, are not applied to the deployed version.
- How do you render a preview once per sample user without writing one function per user?Add a parameter annotated `@PreviewParameter(UserProvider::class)` where `UserProvider` implements `PreviewParameterProvider<User>` and returns the samples from `values`. One preview renders per element. `limit` caps the count, and overriding `getDisplayName()` gives each one a readable name.
- A Compose preview needs a running emulator to render the composable.
- A preview can load real data from the network when the computer is online.
- Hilt builds the ViewModel's dependency graph for the preview automatically.
- backgroundColor in @Preview takes a Color value such as Color.Green.
- Stacking two multipreview annotations renders every combination of their variants.