How to Use Button in Compose in Android: Simple Guide
In Jetpack Compose, use the
Button composable to create clickable buttons. You provide a onClick lambda for the button action and place the button label inside the Button block as a composable, usually Text. This creates a simple, interactive button in your UI.Syntax
The Button composable requires an onClick parameter which is a lambda function triggered when the button is pressed. Inside the Button block, you place the content such as Text to show the button label.
Basic syntax:
Button(onClick = { /* action */ }) { Text("Label") }
kotlin
Button(onClick = { /* Your action here */ }) {
Text("Click me")
}Output
A button labeled 'Click me' that responds to taps.
Example
This example shows a complete Compose app with a button that updates a counter each time it is clicked.
kotlin
import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Column import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.tooling.preview.Preview class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CounterButton() } } } @Composable fun CounterButton() { var count by remember { mutableStateOf(0) } Column { Button(onClick = { count++ }) { Text("Clicked $count times") } } } @Preview(showBackground = true) @Composable fun PreviewCounterButton() { CounterButton() }
Output
A button labeled 'Clicked 0 times' initially, increasing the number each time it is tapped.
Common Pitfalls
Common mistakes when using Button in Compose include:
- Forgetting to provide the
onClickparameter, which causes a compile error. - Placing non-composable content inside the
Buttonblock. - Not managing state properly, so UI does not update on button clicks.
Always use Compose state (like remember and mutableStateOf) to update UI on button clicks.
kotlin
/* Wrong: Missing onClick */ // Button() { // Text("Click me") // } /* Right: onClick provided */ Button(onClick = { /* action */ }) { Text("Click me") }
Quick Reference
Tips for using Button in Compose:
- Use
onClickto handle taps. - Place
Textor other composables inside the button for label or icon. - Use Compose state to update UI dynamically.
- Use
Buttonfrommaterial3ormaterialpackage depending on your design.
Key Takeaways
Use the Button composable with an onClick lambda to create clickable buttons in Compose.
Place composable content like Text inside Button to show the label.
Manage UI changes on button clicks using Compose state such as remember and mutableStateOf.
Always provide the onClick parameter to avoid compile errors.
Use material3 Button for modern Material Design styling.