Sample Data in Compose Previews

Jossi Wolf
Snapp Mobile
Published in
2 min readJul 5, 2020

This post was written for Compose 0.1.0.

Jetpack Compose is Google’s new Android UI Toolkit, currently in development. If you already want to have a look, you can play around with it and learn some exciting new things!

One area where Compose shines is previews. By annotating Composables with @Preview , you can preview the Composables inside Android Studio.

This is very useful when working with e.g. Design Systems, or you just want to explore different variants of your UI components. But often, your Composables will take parameters, like our Project Composable.

In these cases, you can’t use the Preview annotation on your Composable — after all, Compose doesn’t know where to obtain those parameters. One solution to this is to create “wrapper” Composables without any parameters.

This has one big downside: You will end up creating lots of preview Composables, cluttering your code.

In other cases, you might have a list and want to provide some sample data.

With XML, supplying data for the preview was easily doable with the tools namespace.

PreviewParameter to the Rescue

Luckily, Jetpack Compose has the @PreviewParameter annotation. It can be applied to any parameter of a @Preview.

It needs PreviewParameterProvider , a simple interface which we can implement.

Finally, we can use the @Preview annotation with our @PreviewParameter -annotated arguments.

One caveat is that @PreviewParameter is only allowed on one parameter of a function, which is why we assign a default value to our second parameter.

With this, previews become a lot more powerful in Compose. Let me know if this is useful in your day-to-day work and comment with any thoughts on this!

--

--

Jossi Wolf
Snapp Mobile

Software Engineer @Google working on Jetpack Compose. I like Kotlin, Animations and Rabbits! speakerdeck.com/jossiwolf