Jetpack Compose with Copilot: Create a button to increment a counter
Video: Jetpack Compose with Copilot: Create a button to increment a counter by Taught by Celeste AI - AI Coding Coach
Watch full page →Jetpack Compose with Copilot: Create a Button to Increment a Counter
In Jetpack Compose, managing state and updating the UI reactively is straightforward. This example demonstrates how to create a simple button that increments a counter each time it is clicked, showcasing Compose's declarative approach to UI development.
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
import androidx.compose.ui.tooling.preview.Preview
@Composable
fun CounterButton() {
// Remember the current count state
val count = remember { mutableStateOf(0) }
Button(onClick = { count.value++ }) {
Text("Clicked ${count.value} times")
}
}
@Preview(showBackground = true)
@Composable
fun PreviewCounterButton() {
CounterButton()
}
Key Points
- Use
rememberwithmutableStateOfto hold and observe state in Compose. - The UI automatically recomposes when the state changes, updating the displayed count.
Buttoncomposable accepts anonClicklambda to handle user interaction.- Text inside the button dynamically shows the current count, reflecting state changes instantly.
@Previewannotation helps visualize composables during development without running the full app.