0
0
Android Kotlinmobile~5 mins

Button composable in Android Kotlin

Choose your learning style9 modes available
Introduction

A Button lets users tap to do something, like sending a message or opening a screen.

When you want the user to submit a form.
When you want to trigger an action like saving data.
When you want to navigate to another screen.
When you want to confirm or cancel a choice.
Syntax
Android Kotlin
Button(onClick = { /* action here */ }) {
    Text("Button Label")
}

The onClick is what happens when the user taps the button.

The content inside the button is usually a Text showing the label.

Examples
A simple button that prints "Clicked" when tapped.
Android Kotlin
Button(onClick = { println("Clicked") }) {
    Text("Click me")
}
A button labeled "Submit" for sending data.
Android Kotlin
Button(onClick = { /* do something */ }) {
    Text("Submit")
}
A button labeled "Next" to go to another screen.
Android Kotlin
Button(onClick = { /* open screen */ }) {
    Text("Next")
}
Sample App

This program shows a button labeled "Press me". When tapped, it prints "Button pressed" in the console.

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

@Composable
fun SimpleButton() {
    Button(onClick = { println("Button pressed") }) {
        Text("Press me")
    }
}

@Preview
@Composable
fun PreviewSimpleButton() {
    SimpleButton()
}
OutputSuccess
Important Notes

Buttons should have clear labels so users know what will happen.

You can customize buttons with colors and shapes using parameters.

Use enabled = false to disable a button so it can't be tapped.

Summary

Buttons let users tap to do actions.

Use Button(onClick = { }) with a Text label inside.

Always give buttons clear and simple labels.