Reputation: 1370
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?
Upvotes: 8
Views: 2039
Reputation: 355
You can use the preview parameters
@Preview
@Composable
private fun TextPreview(@PreviewParameter(LoremIpsum::class) text: String) {
Box(
modifier = Modifier
.size(128.dp)
.background(Color.LightGray)
.padding(8.dp),
) {
Text(text = text, overflow = TextOverflow.Ellipsis)
}
}
Source: https://c306.net/thewinterblog/2023/01/18/lorem-ipsum-text-for-compose-previews/
Upvotes: 0
Reputation: 29885
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:
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.
Upvotes: 1