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:
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 function is annotated with the @Composable annotation. All Composable functions must have this annotation; this annotation informs the Compose compiler that this function is intended to convert data into UI. The function takes in data.
Jetpack Compose is built around composable functions. These functions let you define your app's UI programmatically by describing how it should look and providing data dependencies, rather than focusing on the process of the UI's construction (initializing an element, attaching it to a parent, etc.).
It is very simple to create a Preview in Compose, simply annotate a Composable function with “@Preview” annotation and call the Composable function that you want to render on your editor or screen. Eg. Looks very clean and simple.
You should not pass ViewModel instances to other composables. Using the rule, we must pass ViewModel to a screen-level composable. Usually, screen-level composable consists of Activity or Fragment. Hence, this is how we implement ViewModel to View in our application.
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With