UI
The user interface is built by defining a set of @Composable functions that take in data and emit UI elements.
Rather than reading about each concept in the abstract, we’ll build a small working app and meet the concepts as we need them, using the FizzBuzz kata as our use case.
|
Note
|
The original kata is only about the algorithm: print the numbers from 1 to N, replacing multiples of 3 with "Fizz", multiples of 5 with "Buzz", and multiples of both with "FizzBuzz". To have something worth building a UI around, we’ll make the two divisors and the upper bound configurable instead of hardcoding them, and generate the sequence on demand. |
@Composable functions
A @Composable function describes a UI element.
Calling it doesn’t build and hand back a view you then have to attach somewhere.
It tells Compose what should be on screen for the data it was given, and Compose takes care of actually drawing it.
That’s why these functions return Unit (i.e. nothing): their useful effect is emitting UI as they run, not producing a value.
1@Composable
2fun FizzBuzzHeader() {
3 Column {
4 Text(
5 text = "FizzBuzz", style = MaterialTheme.typography.headlineLarge
6 )
7
8 Text(
9 text = "Generate your own FizzBuzz sequence!"
10 )
11 }
12}Text displays text, here styled with one of MaterialTheme's predefined typography styles.
Column is a layout composable: it stacks the composables in its body vertically, one below the other.
Capturing input: OutlinedTextField
To let the user pick a maximum and the two divisors, we need text fields.
We wrap OutlinedTextField in our own NumberInput composable so we don’t repeat its configuration three times:
1@Composable
2fun NumberInput(
3 label: String, value: String, onValueChange: (String) -> Unit
4) {
5 OutlinedTextField(
6 value = value,
7 onValueChange = onValueChange,
8 label = { Text(label) },
9 keyboardOptions = KeyboardOptions(
10 keyboardType = KeyboardType.Number
11 ),
12 singleLine = true,
13 modifier = Modifier.fillMaxWidth()
14 )
15}Notice that NumberInput takes its value and an onValueChange callback as parameters rather than holding any state itself.
Spacing things out: Arrangement
FizzBuzzConfiguration calls NumberInput three times, once per field, inside a Column.
Arrangement.spacedBy tells the Column how much breathing room to leave between its children:
1@Composable
2fun FizzBuzzConfiguration(
3 maximum: String,
4 fizzDivisor: String,
5 buzzDivisor: String,
6 onMaximumChange: (String) -> Unit,
7 onFizzDivisorChange: (String) -> Unit,
8 onBuzzDivisorChange: (String) -> Unit
9) {
10 Column(
11 verticalArrangement = Arrangement.spacedBy(12.dp)
12 ) {
13 Text(
14 text = "Configuration", style = MaterialTheme.typography.titleMedium
15 )
16
17 NumberInput(
18 label = "Maximum number", value = maximum, onValueChange = onMaximumChange
19 )
20
21 NumberInput(
22 label = "Fizz divisor", value = fizzDivisor, onValueChange = onFizzDivisorChange
23 )
24
25 NumberInput(
26 label = "Buzz divisor", value = buzzDivisor, onValueChange = onBuzzDivisorChange
27 )
28 }
29}Displaying a list: LazyColumn
Once generated, the results are displayed as a scrollable list.
Unlike Column, LazyColumn only creates and lays out the items that are actually visible on screen, which matters once the list gets long.
1@Composable
2fun FizzBuzzResults(
3 results: List<String>
4) {
5 Column {
6 Text(
7 text = "Results", style = MaterialTheme.typography.titleMedium
8 )
9
10 LazyColumn() {
11 items(results) { it -> FizzBuzzItem(it) }
12 }
13 }
14}
15
16@Composable
17fun FizzBuzzItem(value: String) {
18 Card {
19 Box(
20 modifier = Modifier
21 .padding(12.dp)
22 .fillMaxWidth(), contentAlignment = Alignment.Center
23 ) {
24 Text(value)
25 }
26 }
27}Card draws a surface with a default elevation and shape around its content.
Box overlays its children instead of stacking or listing them; here it has a single child, which contentAlignment = Alignment.Center centers both horizontally and vertically.
Triggering an action: Button, and tying it together with Scaffold
Generating the sequence happens when the user taps a Button.
The screen itself is assembled from the pieces above, and the whole app starts from a Scaffold, which reserves space for system bars (status bar, navigation bar) and hands us an innerPadding to apply so our content doesn’t get drawn underneath them:
1class MainActivity : ComponentActivity() {
2 override fun onCreate(savedInstanceState: Bundle?) {
3 super.onCreate(savedInstanceState)
4 enableEdgeToEdge()
5 setContent {
6 FizzBuzzTheme {
7 Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
8 FizzBuzzScreen(modifier = Modifier.padding(innerPadding))
9 }
10 }
11 }
12 }
13}
14
15@Composable
16fun FizzBuzzScreen(modifier: Modifier = Modifier) {
17 var maximum by remember { mutableStateOf("100") }
18 var fizzDivisor by remember { mutableStateOf("3") }
19 var buzzDivisor by remember { mutableStateOf("5") }
20 var results by remember { mutableStateOf(emptyList<String>()) }
21
22 Column(modifier = modifier) {
23 FizzBuzzHeader()
24 FizzBuzzConfiguration(
25 maximum = maximum,
26 fizzDivisor = fizzDivisor,
27 buzzDivisor = buzzDivisor,
28 onMaximumChange = { maximum = it },
29 onFizzDivisorChange = { fizzDivisor = it },
30 onBuzzDivisorChange = { buzzDivisor = it })
31 Button(onClick = {
32 results = fizzBuzz(
33 maximum.toIntOrNull() ?: 100,
34 fizzDivisor.toIntOrNull() ?: 3,
35 buzzDivisor.toIntOrNull() ?: 5
36 )
37 }) {
38 Text(text = "Generate")
39 }
40 FizzBuzzResults(results = results)
41 }
42}FizzBuzzScreen is where the whole tree comes together: it calls FizzBuzzHeader(), FizzBuzzConfiguration(…), and FizzBuzzResults(…) — each a small, independent, reusable @Composable function, exactly as we built them above.
Event handlers and state hoisting
Look again at FizzBuzzScreen: the three remember { mutableStateOf(…) } variables and the results list live here, in the parent — not inside NumberInput or FizzBuzzConfiguration.
Those children only receive a value and an onValueChange/onClick callback; when the user types or taps, the callback runs in FizzBuzzScreen and updates its state.
This pattern is called state hoisting: state is lifted up to the lowest common ancestor that needs it, and pushed back down as plain parameters and callbacks. The children become simple, reusable, and easy to test in isolation, because they don’t own any state themselves — there’s a single source of truth. We’ll go much further into state management — including surviving configuration changes and process death — in State; for now, just remember that event handlers are how user actions turn into state changes.
Recomposition
When maximum, fizzDivisor, buzzDivisor, or results changes, Compose doesn’t redraw the whole screen from scratch: it re-invokes only the @Composable functions that actually read the piece of state that changed, and skips the rest.
This process is called recomposition.
It’s the mechanism that makes a declarative UI like this one stay in sync with its state.
Previewing a composable
Adding @Preview to a @Composable function lets Android Studio render it directly in the editor, without running the app on a device or emulator.
@Preview functions take no parameters, so they’re a good fit for small, self-contained composables such as FizzBuzzItem:
1@Preview
2@Composable
3fun FizzBuzzItemPreview() {
4 FizzBuzzTheme {
5 FizzBuzzItem(value = "FizzBuzz")
6 }
7}Put together, these pieces make up a complete, working app: download FizzBuzzMVP.kt.
From MVP to a polished UI
The MVP above gets the mechanics right, but the UX is lacking: nothing stops the user from entering a negative maximum or a zero divisor, and the layout is plain.
The second version, FizzBuzzFinal.kt, builds on the same state model and function structure and adds:
-
Input validation: the button’s
onClicknow checks the parsed values and stores a message in a newerrorstate instead of generating a sequence when they’re invalid. -
Material styling:
Card,RoundedCornerShape,Spacer, typography weights andMaterialTheme.colorSchemecolors give the screen visual hierarchy, andFizzBuzzResultsswitches from aLazyColumnto aLazyVerticalGridso results tile across the screen instead of stacking one per line.
1package com.ingeniouscontraptions.emse.fizzbuzz
2
3import android.os.Bundle
4import androidx.activity.ComponentActivity
5import androidx.activity.compose.setContent
6import androidx.activity.enableEdgeToEdge
7import androidx.compose.foundation.layout.Arrangement
8import androidx.compose.foundation.layout.Box
9import androidx.compose.foundation.layout.Column
10import androidx.compose.foundation.layout.PaddingValues
11import androidx.compose.foundation.layout.Row
12import androidx.compose.foundation.layout.Spacer
13import androidx.compose.foundation.layout.fillMaxSize
14import androidx.compose.foundation.layout.fillMaxWidth
15import androidx.compose.foundation.layout.height
16import androidx.compose.foundation.layout.padding
17import androidx.compose.foundation.lazy.grid.GridCells
18import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
19import androidx.compose.foundation.lazy.grid.items
20import androidx.compose.foundation.shape.RoundedCornerShape
21import androidx.compose.foundation.text.KeyboardOptions
22import androidx.compose.material3.Button
23import androidx.compose.material3.Card
24import androidx.compose.material3.CardDefaults
25import androidx.compose.material3.MaterialTheme
26import androidx.compose.material3.OutlinedTextField
27import androidx.compose.material3.Scaffold
28import androidx.compose.material3.Text
29import androidx.compose.runtime.Composable
30import androidx.compose.runtime.getValue
31import androidx.compose.runtime.mutableStateOf
32import androidx.compose.runtime.remember
33import androidx.compose.runtime.setValue
34import androidx.compose.ui.Alignment
35import androidx.compose.ui.Modifier
36import androidx.compose.ui.text.font.FontWeight
37import androidx.compose.ui.text.input.KeyboardType
38import androidx.compose.ui.unit.dp
39import com.ingeniouscontraptions.emse.fizzbuzz.ui.theme.FizzBuzzTheme
40
41class MainActivity : ComponentActivity() {
42 override fun onCreate(savedInstanceState: Bundle?) {
43 super.onCreate(savedInstanceState)
44 enableEdgeToEdge()
45 setContent {
46 FizzBuzzTheme {
47 Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
48 FizzBuzzScreen(modifier = Modifier.padding(innerPadding))
49 }
50 }
51 }
52 }
53}
54
55@Composable
56fun FizzBuzzScreen(modifier: Modifier = Modifier) {
57 var maximum by remember { mutableStateOf("100") }
58 var fizzDivisor by remember { mutableStateOf("3") }
59 var buzzDivisor by remember { mutableStateOf("5") }
60 var results by remember { mutableStateOf(emptyList<String>()) }
61 var error by remember { mutableStateOf<String?>(null) }
62
63 Column(
64 modifier = modifier
65 .fillMaxSize()
66 .padding(horizontal = 20.dp, vertical = 16.dp)
67 ) {
68 FizzBuzzHeader()
69
70 Spacer(modifier = Modifier.height(20.dp))
71
72 FizzBuzzConfiguration(
73 maximum = maximum,
74 fizzDivisor = fizzDivisor,
75 buzzDivisor = buzzDivisor,
76 onMaximumChange = { maximum = it },
77 onFizzDivisorChange = { fizzDivisor = it },
78 onBuzzDivisorChange = { buzzDivisor = it })
79
80 Spacer(modifier = Modifier.height(16.dp))
81
82 Button(
83 onClick = {
84 val max = maximum.toIntOrNull()
85 val fizz = fizzDivisor.toIntOrNull()
86 val buzz = buzzDivisor.toIntOrNull()
87
88 error = when {
89 max == null || max !in 1..500 -> "Maximum must be between 1 and 500"
90
91 fizz == null || fizz <= 0 -> "Fizz divisor must be positive"
92
93 buzz == null || buzz <= 0 -> "Buzz divisor must be positive"
94
95 else -> null
96 }
97
98 if (error == null) {
99 results = fizzBuzz(max!!, fizz!!, buzz!!)
100 }
101 }, modifier = Modifier
102 .fillMaxWidth()
103 .height(52.dp), shape = RoundedCornerShape(14.dp)
104 ) {
105 Text(
106 text = "Generate", style = MaterialTheme.typography.labelLarge
107 )
108 }
109
110 error?.let {
111 Text(
112 text = it,
113 color = MaterialTheme.colorScheme.error,
114 modifier = Modifier.padding(top = 8.dp)
115 )
116 }
117
118 Spacer(modifier = Modifier.height(24.dp))
119
120 FizzBuzzResults(
121 results = results, modifier = Modifier.weight(1f)
122 )
123 }
124}
125
126@Composable
127fun FizzBuzzHeader() {
128 Column(
129 modifier = Modifier
130 .fillMaxWidth()
131 .padding(vertical = 12.dp),
132 horizontalAlignment = Alignment.CenterHorizontally
133 ) {
134 Text(
135 text = "FizzBuzz",
136 style = MaterialTheme.typography.headlineLarge,
137 fontWeight = FontWeight.ExtraBold,
138 color = MaterialTheme.colorScheme.primary
139 )
140
141 Text(
142 text = "Generate your own FizzBuzz sequence!",
143 style = MaterialTheme.typography.bodyMedium,
144 color = MaterialTheme.colorScheme.onSurfaceVariant
145 )
146 }
147}
148
149@Composable
150fun NumberInput(
151 label: String, value: String, onValueChange: (String) -> Unit, modifier: Modifier = Modifier
152) {
153 OutlinedTextField(
154 value = value,
155 onValueChange = onValueChange,
156 label = { Text(label) },
157 keyboardOptions = KeyboardOptions(
158 keyboardType = KeyboardType.Number
159 ),
160 singleLine = true,
161 shape = RoundedCornerShape(12.dp),
162 modifier = modifier.fillMaxWidth()
163 )
164}
165
166@Composable
167fun FizzBuzzConfiguration(
168 maximum: String,
169 fizzDivisor: String,
170 buzzDivisor: String,
171 onMaximumChange: (String) -> Unit,
172 onFizzDivisorChange: (String) -> Unit,
173 onBuzzDivisorChange: (String) -> Unit
174) {
175 Card(
176 modifier = Modifier.fillMaxWidth(),
177 shape = RoundedCornerShape(20.dp),
178 colors = CardDefaults.cardColors(
179 containerColor = MaterialTheme.colorScheme.surfaceContainer
180 )
181 ) {
182 Column(
183 modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)
184 ) {
185 Text(
186 text = "Configuration",
187 style = MaterialTheme.typography.titleMedium,
188 fontWeight = FontWeight.Bold
189 )
190
191 NumberInput(
192 label = "Maximum number", value = maximum, onValueChange = onMaximumChange
193 )
194
195 Row(
196 horizontalArrangement = Arrangement.spacedBy(12.dp)
197 ) {
198 NumberInput(
199 label = "Fizz divisor",
200 value = fizzDivisor,
201 onValueChange = onFizzDivisorChange,
202 modifier = Modifier.weight(1f)
203 )
204
205 NumberInput(
206 label = "Buzz divisor",
207 value = buzzDivisor,
208 onValueChange = onBuzzDivisorChange,
209 modifier = Modifier.weight(1f)
210 )
211 }
212 }
213 }
214}
215
216@Composable
217fun FizzBuzzResults(
218 results: List<String>, modifier: Modifier = Modifier
219) {
220 Column(modifier = modifier) {
221 Row(
222 modifier = Modifier
223 .fillMaxWidth()
224 .padding(bottom = 12.dp),
225 horizontalArrangement = Arrangement.SpaceBetween,
226 verticalAlignment = Alignment.CenterVertically
227 ) {
228 Text(
229 text = "Results",
230 style = MaterialTheme.typography.titleMedium,
231 fontWeight = FontWeight.Bold
232 )
233
234 Text(
235 text = "${results.size} numbers",
236 style = MaterialTheme.typography.labelMedium,
237 color = MaterialTheme.colorScheme.onSurfaceVariant
238 )
239 }
240
241 if (!results.isEmpty()) {
242 LazyVerticalGrid(
243 columns = GridCells.Fixed(3),
244 modifier = Modifier.fillMaxSize(),
245 horizontalArrangement = Arrangement.spacedBy(8.dp),
246 verticalArrangement = Arrangement.spacedBy(8.dp),
247 contentPadding = PaddingValues(bottom = 16.dp)
248 ) {
249 items(results) { result ->
250 FizzBuzzItem(result)
251 }
252 }
253 }
254 }
255}
256
257
258@Composable
259fun FizzBuzzItem(value: String) {
260 Card {
261 Box(
262 modifier = Modifier
263 .padding(12.dp)
264 .fillMaxWidth(), contentAlignment = Alignment.Center
265 ) {
266 Text(value)
267 }
268 }
269}
270
271fun fizzBuzz(
272 maximum: Int, fizzDivisor: Int = 3, buzzDivisor: Int = 5
273): List<String> = (1..maximum).map { number ->
274 when {
275 number % fizzDivisor == 0 && number % buzzDivisor == 0 -> "FizzBuzz"
276 number % fizzDivisor == 0 -> "Fizz"
277 number % buzzDivisor == 0 -> "Buzz"
278 else -> number.toString()
279 }
280}Styling and validation were simply layered on top of that skeleton.