简体   繁体   中英

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:

  • To use multiple custom previews only while developing.
  • Partially reuse the previews - use compile-time constants for name and group.

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

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")
}

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM