Skip to content
DeveloperMemos

Checking if a Composable is rendering in a Preview

Android, Jetpack, Compose, Kotlin1 min read

Previews are one of the best parts about Jetpack Compose and sometimes you might want to check if a Composable is being rendered in a @Preview or not.

When I first started using Compose sometimes I would add a isPreview parameter to my Composables and set it to true inside my @Preview, kind of like this:

1@Composable
2fun ExampleView(
3 isPreview: Boolean = false
4) {
5 if (isPreview) {
6 Text("This is a preview")
7 } else {
8 Text("This is not")
9 }
10}
11
12@Preview
13@Composable
14fun ExampleViewPreview() {
15 ExampleView(
16 isPreview = true
17 )
18}

I actually found out recently that this isn't necessary so I was able to refactor some of my Composables.

Instead of setting an extra parameter you can just check LocalInspectionMode.current which will return true if the Composable is being rendered in preview mode(or more specifically an inspectable component - you can check out the documentation here).

Using LocalInspectionMode.current

Here's a quick example using the ExampleView Composable from above:

1@Composable
2fun ExampleView(
3 isPreview: Boolean = LocalInspectionMode.current
4) {
5 if (isPreview) {
6 Text("This is a preview")
7 } else {
8 Text("This is not")
9 }
10}

And this is the preview:

1@Preview
2@Composable
3fun ExampleViewPreview() {
4 ExampleView()
5}

And when this gets rendered in the preview view the text "This is a preview" will be displayed.

Compose Preview

And when you run the app on an emulator or test device you should get "This is not" instead.