Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

How to create multiple previews of a composable in Android Jetpack Compose?

An Android Jetpack composable may have parameters and it would be great to have multiple previews of a single composable to see how it works with different arguments. Let's take for example a simple composable:

@Composable
fun GreetingText(name: String) {
    Text("Hello $name!")
}

A preview might look like this:

@Preview
@Composable
fun GreetingTextPreview() {
    GreetingText("John")
}

How can I preview the composable using different names without creating multiple previews?

question from:https://stackoverflow.com/questions/65902942/how-to-create-multiple-previews-of-a-composable-in-android-jetpack-compose

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Single preview composable

A straightforward way is to combine multiple composables in a single preview, for example:

@Preview(showBackground = true)
@Composable
fun GreetingTextPreview() {
    Column {
        val names = remember {
            arrayOf("John", "D'Artagnan")
        }

        for (name in names) {
            GreetingText(name)
        }
    }
}

The result:

enter image description here

Multiple previews using PreviewParameter

It might not be convenient to combine multiple composables into a single preview if the composable is too large for example. An alternative way is to use a PreviewParameter, this way you'll get separate previews:

class NameProvider: PreviewParameterProvider<String> {
    override val values: Sequence<String> = sequenceOf(
        "John",
        "Albert Einstein"
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingTextPreview(
    @PreviewParameter(NameProvider::class) name: String
) {
    GreetingText(name)
}

And the result:

enter image description here

But keep in mind that you're limited to have only one @PreviewParameter per preview composable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...