0
0
Android Kotlinmobile~15 mins

Preview annotation in Android Kotlin - Mini App: Build & Ship

Choose your learning style9 modes available
Build: PreviewAnnotationScreen
This screen demonstrates how to use the @Preview annotation in Jetpack Compose to see a preview of a composable function in Android Studio.
Target UI
-------------------------
| Preview Annotation    |
|-----------------------|
| Hello, Jetpack Compose |
|                       |
| [Button: Click Me]    |
-------------------------
Create a composable function that displays a greeting text and a button.
Use the @Preview annotation to enable preview in Android Studio.
The button should have the label 'Click Me'.
Starter Code
Android Kotlin
import androidx.compose.material3.*
import androidx.compose.runtime.Composable

// TODO: Add your composable function here

// TODO: Add your @Preview annotated function here
Task 1
Task 2
Solution
Android Kotlin
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview

@Composable
fun GreetingScreen() {
  Column(
    modifier = androidx.compose.ui.Modifier.padding(16.dp)
  ) {
    Text(text = "Hello, Jetpack Compose")
    Spacer(modifier = androidx.compose.ui.Modifier.height(8.dp))
    Button(onClick = {}) {
      Text(text = "Click Me")
    }
  }
}

@Preview(showBackground = true)
@Composable
fun GreetingScreenPreview() {
  GreetingScreen()
}

We created a composable function GreetingScreen that shows a text and a button vertically using a Column. We added padding and spacing for better layout.

The @Preview annotation on GreetingScreenPreview allows Android Studio to render this composable in the design preview pane. The showBackground = true parameter adds a background so the preview is clearer.

This setup helps developers see UI changes instantly without running the app on a device or emulator.

Final Result
Completed Screen
-------------------------
| Preview Annotation    |
|-----------------------|
| Hello, Jetpack Compose |
|                       |
| [Button: Click Me]    |
-------------------------
Tapping the 'Click Me' button currently does nothing (empty onClick handler).
Preview in Android Studio shows this UI without running the app.
Stretch Goal
Add a second @Preview function that shows the GreetingScreen in dark mode.
💡 Hint
Use @Preview(uiMode = Configuration.UI_MODE_NIGHT_YES) to enable dark mode preview.