Mastering Jetpack Compose Preview: Pro Tips and Tricks

Jetpack Compose makes building Android app screens easier. One of its cool features is the @Preview annotation. This lets us quickly see how our designs look without running the full app. But sometimes, we need to see our designs in different ways, like in dark mode or light mode. Repeating the same settings for every component can get messy. That's where custom annotations come in.

1- Context-Aware Previews: Light and Dark Theme

For instance, most apps nowadays support both light and dark themes. Previewing a component in both themes typically looks like this:

@Preview(
    name = "Dark Mode",
    showBackground = true,
    uiMode = UI_MODE_NIGHT_YES
)
@Preview(
    name = "Light Mode",
    showBackground = true,
    uiMode = UI_MODE_NIGHT_NO
)
@Composable
fun PreviewListItem() {
    // Your Composable here
}

That’s a chunk of code, especially if you need to replicate this across multiple components. Let’s encapsulate this with a custom annotation:

@Preview(name = "Dark Mode", showBackground = true, uiMode = UI_MODE_NIGHT_YES)
@Preview(name = "Light Mode", showBackground = true, uiMode = UI_MODE_NIGHT_NO)
annotation class ThemePreviews

@ThemePreviews
@Composable
fun PreviewsListItem() {
    MaterialTheme {
        Surface {
            PortraitListItem(
                imageResource = painterResource(id = R.drawable.task),
                text = "Write the `Preview` Medium article",
                isChecked = false,
                onCheckedChange = { }
            )
        }
    }
}

You can get the code for PortraitListItem here:
https://gist.github.com/mo0rti/260c35752a3718d54e774ab3ccbc0179

With the @ThemePreviews your preview looks like this:

 

2- Device Orientations Previews: Portrait & Landscape

Jetpack Compose usually shows previews in the up-and-down portrait style. But you can make your component adaptive on both Landscape and Portrait. We can use LocalConfiguration context within the @Composable function and create an Adaptive compose component.

Read More