Fast Compose

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:

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

Keep going

Open the playground to try 21 more examples: lists, dialogs, animations, gestures and Canvas drawing.