Jetpack Compose: Create a button with a callback
Video: Jetpack Compose: Create a button with a callback by Taught by Celeste AI - AI Coding Coach
Watch full page →Jetpack Compose: Create a Button with a Callback
In Jetpack Compose, buttons are simple to create and can trigger actions through callbacks. This example demonstrates how to define a button that executes a function when clicked, enabling interactive UI behavior in your Compose app.
Code
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
@Composable
fun GreetingButton(onClickAction: () -> Unit) {
// Button with a text label and a click callback
Button(onClick = { onClickAction() }) {
Text("Click me")
}
}
Key Points
- Use the Button composable to create clickable buttons in Jetpack Compose.
- Pass a lambda function as the onClick parameter to handle button clicks.
- Callbacks allow separation of UI and logic, making components reusable.
- The Button content can be customized with any composable, here using Text.