Mastering Jetpack Compose Preview: Pro Tips and Tricks

<p>Jetpack Compose makes building Android app screens easier. One of its cool features is the&nbsp;<code>@Preview</code>&nbsp;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&#39;s where custom annotations come in.</p> <h1>1- Context-Aware Previews: Light and Dark Theme</h1> <p>For instance, most apps nowadays support both light and dark themes. Previewing a component in both themes typically looks like this:</p> <pre> @Preview( name = &quot;Dark Mode&quot;, showBackground = true, uiMode = UI_MODE_NIGHT_YES ) @Preview( name = &quot;Light Mode&quot;, showBackground = true, uiMode = UI_MODE_NIGHT_NO ) @Composable fun PreviewListItem() { // Your Composable here }</pre> <p>That&rsquo;s a chunk of code, especially if you need to replicate this across multiple components. Let&rsquo;s encapsulate this with a custom annotation:</p> <pre> @Preview(name = &quot;Dark Mode&quot;, showBackground = true, uiMode = UI_MODE_NIGHT_YES) @Preview(name = &quot;Light Mode&quot;, showBackground = true, uiMode = UI_MODE_NIGHT_NO) annotation class ThemePreviews @ThemePreviews @Composable fun PreviewsListItem() { MaterialTheme { Surface { PortraitListItem( imageResource = painterResource(id = R.drawable.task), text = &quot;Write the `Preview` Medium article&quot;, isChecked = false, onCheckedChange = { } ) } } }</pre> <blockquote> <p>You can get the code for&nbsp;<strong>PortraitListItem</strong>&nbsp;here:<br /> <a href="https://gist.github.com/mo0rti/260c35752a3718d54e774ab3ccbc0179" rel="noopener ugc nofollow" target="_blank">https://gist.github.com/mo0rti/260c35752a3718d54e774ab3ccbc0179</a></p> </blockquote> <p>With the&nbsp;<code>@ThemePreviews</code>&nbsp;your preview looks like this:</p> <p>&nbsp;</p> <h1>2- Device Orientations Previews: Portrait &amp; Landscape</h1> <p>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&nbsp;<code>LocalConfiguration</code>&nbsp;context within the&nbsp;<code>@Composable</code>&nbsp;function and create an Adaptive compose component.</p> <p><a href="https://medium.com/@mortitech/better-previews-in-compose-with-custom-annotations-dc49b94ff579">Read More</a></p>