Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tools Attributes - Sample resources in Jetpack Compose

In the View world we could use the @tools:sample/* resources to get sample texts, like full_names, first_names, cities, dates and so on.

These annotations were used, afaik, by Android Studio layout editor to be able to see mock data on the editor.

In the Compose world there is no xml, therefore no @tools:sample/*.

Is there any way for Android Studio to still use those sample test inside the @Composable functions? Or is there any other built in solution for Compose?

like image 265
Kuruchy Avatar asked Jul 03 '26 20:07

Kuruchy


1 Answers

There are a few solutions. You can either use the @PreviewParameter or simply write code in your preview composable to generate the desired data. Personally, I never use Preview mode and if I did, I would probably just write custom code inside of it to create the desired data.

@PreviewParameter:

You can use the @PreviewParameter annotation to create mock data for your preview. Here's an article on how to do this.

https://medium.com/snapp-mobile/sample-data-in-compose-previews-bec32b62370f

Also, see this post:

How to use the @PreviewParameter annotation?

NOTE: You can only use on @PreviewParameter per composable function. Kind of makes it useless.

Custom code:

@Preview
@Composable
fun MyList() {
    Column() {
        repeat(5) {
            Text("Number: " + it.toString())
        }
    }
}

In this example, I'm just showing a Text composable. But you can replace it with your own custom composable and pass in custom data for all the parameters.

A more advanced solution to generating a variety of custom data such as images, names, text, numbers etc, is to retrieve the data from a backend API. You can use Wirespec. It provides JSON data and already has many built-in data types:

https://wirespec.dev

Here for example is an API that provides mock weather data:

https://api.wirespec.dev/wirespec/weather/getweather

And here's the API that generates the data:

https://wirespec.dev/Wirespec/projects/apis/Weather/apis/getWeather

Here's one that generates a list of random books: https://api.wirespec.dev/wirespec/books/getbooks https://wirespec.dev/Wirespec/projects/apis/Books/apis/getBooks

You can create your own custom data sources on Wirespec.

like image 64
Johann Avatar answered Jul 06 '26 09:07

Johann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!