Lesson 3
Button and State
A UI has to react when the user taps something. In Compose, you keep the changing values in state, and the screen updates whenever the state changes.
Button
Button takes an onClick lambda, which runs on every click, and its content
in braces:
This button does nothing yet, because its onClick is empty.
State: a counter
To show how many times the button was clicked, keep the count in state:
Click the button above. Here's what happens:
mutableStateOf(0)creates a value that Compose watches, starting at 0.rememberkeeps it when the UI is drawn again. Without it, the count would reset to 0 every time.bylets you usecountlike a normal variable.count++changes the state, so Compose runs the code again and shows the new number. This is called recomposition.
State: a toggle
State can hold any value. Here a Boolean switches between two looks:
The icon, its color and the text all read liked, so one click updates all three.
The rule of state: don't change the UI directly. Change the state, and let Compose redraw the UI from it.
Summary
Button(onClick = { … })runs code on click.var x by remember { mutableStateOf(…) }keeps a value that can change.- Changing state updates every part of the UI that reads it.
Keep going
Open the playground to try 21 more examples: lists, dialogs, animations, gestures and Canvas drawing.
Fast Compose