Mastering Jetpack Compose Preview: Pro Tips and Tricks
<p>Jetpack Compose makes building Android app screens easier. One of its cool features is the <code>@Preview</code> 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.</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 = "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
}</pre>
<p>That’s a chunk of code, especially if you need to replicate this across multiple components. Let’s encapsulate this with a custom annotation:</p>
<pre>
@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 = { }
)
}
}
}</pre>
<blockquote>
<p>You can get the code for <strong>PortraitListItem</strong> 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 <code>@ThemePreviews</code> your preview looks like this:</p>
<p> </p>
<h1>2- Device Orientations Previews: Portrait & 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 <code>LocalConfiguration</code> context within the <code>@Composable</code> 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>