Create a button with a callback that shows that it is clicked #Jetpack compose
Video: Create a button with a callback that shows that it is clicked #Jetpack compose by Taught by Celeste AI - AI Coding Coach
Watch full page →Create a Button with a Callback That Shows It Is Clicked in Jetpack Compose
This example demonstrates how to create a simple button in Jetpack Compose that updates its text when clicked. By using Compose’s state management, the button label changes dynamically to indicate that it has been clicked.
Code
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@Composable
fun ClickableButton() {
// Remember the button's clicked state
val clicked = remember { mutableStateOf(false) }
Button(
onClick = {
// Update the clicked state when button is pressed
clicked.value = true
}
) {
// Show different text based on clicked state
if (clicked.value) {
Text("Clicked!")
} else {
Text("Click me")
}
}
}
Key Points
- Use `remember` and `mutableStateOf` to hold and update UI state in Compose.
- The `Button` composable accepts an `onClick` lambda that triggers when the user taps it.
- Changing state causes Compose to recompose and update the UI automatically.
- Conditional UI inside the button lets you show different text based on state.