0
0
Android Kotlinmobile~5 mins

Composable functions in Android Kotlin

Choose your learning style9 modes available
Introduction

Composable functions help you build your app's user interface by combining small pieces together. They make UI code simple and easy to understand.

When you want to create a button, text, or image on the screen.
When you want to build a screen by putting smaller UI parts together.
When you want to update the UI quickly when data changes.
When you want to reuse UI parts in different places.
When you want your app to look good on different screen sizes.
Syntax
Android Kotlin
@Composable
fun Greeting(name: String) {
    Text(text = "Hello, $name!")
}

Use the @Composable annotation to mark a function as composable.

Composable functions describe what the UI should look like.

Examples
This function shows a simple text greeting with the given name.
Android Kotlin
@Composable
fun Greeting(name: String) {
    Text(text = "Hello, $name!")
}
This function uses two Greeting composables inside a column to show two greetings stacked vertically.
Android Kotlin
@Composable
fun WelcomeScreen() {
    Column {
        Greeting("Alice")
        Greeting("Bob")
    }
}
This shows a button with text inside. When clicked, it can run code.
Android Kotlin
@Composable
fun ButtonExample() {
    Button(onClick = { /* do something */ }) {
        Text("Click me")
    }
}
Sample App

This app shows three greetings stacked vertically: Hello, Alice! Hello, Bob! and Hello, Charlie!.

Android Kotlin
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.Column

@Composable
fun Greeting(name: String) {
    Text(text = "Hello, $name!")
}

@Composable
fun GreetingList() {
    Column {
        Greeting("Alice")
        Greeting("Bob")
        Greeting("Charlie")
    }
}

@Preview
@Composable
fun PreviewGreetingList() {
    GreetingList()
}
OutputSuccess
Important Notes

Composable functions can call other composable functions to build complex UIs.

Use @Preview to see your composable UI in Android Studio without running the app.

Composable functions should be short and focused on one UI part for easy reuse.

Summary

Composable functions build UI by combining small pieces.

Mark them with @Composable annotation.

They help create reusable and easy-to-read UI code.