androidandroid-jetpack-composeandroid-jetpack-compose-preview

Reuse a single set of preview annotations in Jetpack Compose across composable functions


Taking first steps in Jetpack Compose, which is quite amazing except one annoying issue.

I have a constant set of previews: Normal, Dark and RTL:

@Preview(
    name = "Normal",
    group = "Screen",
    showBackground = true
)
@Preview(
    name = "Dark",
    group = "Screen",
    showBackground = true,
    uiMode = Configuration.UI_MODE_NIGHT_YES
)
@Preview(
    name = "RTL",
    group = "Screen",
    showBackground = true,
    locale = "iw"
)
@Composable
fun JustAComposable() {
   ...
}

Let's just say, for example that I preview 50 composable functions. I need to copy-paste this set 50 times, which is absolutely incorrect.

Annotation inheritance is forbidden, so my question is: did anybody find a way to reuse the same set of previews across all composable functions?

The only 2 solutions which I could think of are:

Edit:

I created a feature request to compose team to be able to create custom annotation and annotate the annotation with all of the previews I want to reuse.

This way I only need to use my custom annotation.

Can be tracked in Google Issue Tracker


Solution

  • The accepted feature request is now implemented and is available starting from Android Studio Dolphin and Jetpack Compose 1.2.0-beta01.

    It is called Multipreview Annotation. More information about this feature can be found here.

    In order to use this feature, you must create a custom annotation class.

    @Preview(
        name = "small font",
        group = "font scales",
        fontScale = 0.5f
    )
    @Preview(
        name = "large font",
        group = "font scales",
        fontScale = 1.5f
    )
    annotation class FontScalePreviews
    

    and now you can apply this annotation class. For example:

    @FontScalePreviews
    @Composable
    fun HelloWorldPreview() {
        Text("Hello World")
    }
    

    enter image description here