— Android, Jetpack, Compose, Kotlin — 1 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@Composable2fun ExampleView(3 isPreview: Boolean = false4) {5 if (isPreview) {6 Text("This is a preview")7 } else {8 Text("This is not")9 }10}11
12@Preview13@Composable14fun ExampleViewPreview() {15 ExampleView(16 isPreview = true17 )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).
Here's a quick example using the ExampleView Composable from above:
1@Composable2fun ExampleView(3 isPreview: Boolean = LocalInspectionMode.current4) {5 if (isPreview) {6 Text("This is a preview")7 } else {8 Text("This is not")9 }10}
And this is the preview:
1@Preview2@Composable3fun ExampleViewPreview() {4 ExampleView()5}
And when this gets rendered in the preview view the text "This is a preview" will be displayed.
And when you run the app on an emulator or test device you should get "This is not" instead.