How to preview your UI in Compose multiplatform (Android studio / Intellij)

If you use compose multiplatform you might face the issue of not being able to preview your common code UI as its not officially supported yet. you can use Fleet to get a preview but i prefere Android Studio. here is how you can have previews in your common code in 2 simple steps.

Video tutorial

1.Creating our annotation

In your compose multiplatform project go to composeApp > commonMain > kotlin and create a new nasted directories “androidx/compose/desktop/ui/tooling/preview” (you can copy and paste this to the new directory box)

create a new kotlin file called Preview, in this file create an expectation class like below:

package androidx.compose.desktop.ui.tooling.preview


@OptIn(ExperimentalMultiplatform::class)
@OptionalExpectation
expect annotation class Preview()

2.Install the plugin

Install the Multiplatform IDE support plugin from the marketplace.

Finally use the annotation in common main!, make sure to import our newly created annotation instead of the one the comes from “org.jetbrains.compose.ui.tooling.preview.Preview”. now all you need to do is click on the little compose icon that appears next to your function name and you should see the preview window with your preview.

3.Refreshing the preview with a keystroke (optional)

Open android studio settings and go to keymap and search for “previewaction” you should see the action from the ide like below, right click on it and add your keystroke and press ok. now you should be able to refresh the preview with your keyboard shortcut without clicking on the icon with your mouse.

Thats it! if you find this useful comment below!

5 3 votes
Article Rating
Subscribe
Notify of
guest

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
magomed

Это только для Desktop?

Henri

Great article! A common Preview class comes built-in now, however it does not have the showBackground parameter. I used your method to override it, and sommer copied the signature from the Android documentation to add others I might need in future (the ones that don’t have fiddly undefined annotations themselves anyway), and it worked a treat!

package org.jetbrains.compose.ui.tooling.preview

@Suppress(“EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING”)
@OptIn(ExperimentalMultiplatform::class)
@OptionalExpectation
expect annotation class Preview(
val name: String = “”,
val group: String = “”,
val apiLevel: Int = -1,
val widthDp: Int = -1,
val heightDp: Int = -1,
val locale: String = “”,
val fontScale: Float = 1f,
val showSystemUi: Boolean = false,
val showBackground: Boolean = false,
val backgroundColor: Long = 0,
val uiMode: Int = 0,
)
*note the new package name

Last edited 21 days ago by Henri