Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 104 ยท Building a Real UI

Buttons, Text Fields and Forms

Build interactive Compose forms: Material 3 button variants, TextField with keyboard options, IME actions and focus, validation state, checkboxes, switches and sliders.

Most apps are, at heart, forms: sign in, search, create a note, change a setting. In Compose a form is made from a handful of input composables (buttons, text fields, checkboxes, switches and sliders) plus state that you hold. Because of state hoisting, the widgets do not remember anything for you: they show the value you pass and tell you when the user wants to change it.

This lesson covers the Material 3 inputs, the keyboard and focus settings that make a form comfortable to fill in, and a clean way to model validation. The Compose code needs the Android SDK, so it is read-only. The TryIt blocks are Kotlin stand-ins that model the form logic: a reducer-driven validation state machine and a focus and keyboard-action simulation. Pure logic like this is exactly the part you can test without a device.

Buttons

Material 3 has five button styles for different emphasis. Pick by importance, not by looks:

Composable Emphasis Typical use
Button High (filled) The one main action on the screen
FilledTonalButton Medium-high Secondary action next to a main one
ElevatedButton Medium A button on a patterned background that needs a shadow
OutlinedButton Medium Alternative actions such as "Cancel"
TextButton Low Dialog actions, inline links

IconButton (and FilledIconButton) hold a single icon and need a content description for screen readers. Every button takes onClick, an enabled flag, and a content lambda:

Kotlin
// read-only example: needs Compose and Material 3
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
    OutlinedButton(onClick = onCancel) { Text("Cancel") }
    Button(onClick = onSave, enabled = canSave) { Text("Save") }
}

Button(onClick = onSend) {
    Icon(Icons.AutoMirrored.Filled.Send, contentDescription = null)
    Spacer(Modifier.width(8.dp))
    Text("Send")
}

A disabled button does not respond to taps and is drawn dimmed. Computing enabled from state (canSave) is more helpful than letting the user tap and then showing an error, but a disabled button gives no explanation, so show the reason near the field.

Text fields

TextField (filled) and OutlinedTextField are the Material text inputs. Both are stateless: value and onValueChange are required, and you keep the text in state, as the earlier lesson showed.

Kotlin
// read-only example: needs Compose and Material 3
@Composable
fun EmailField(
    email: String,
    error: String?,
    onEmailChange: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    OutlinedTextField(
        value = email,
        onValueChange = onEmailChange,
        modifier = modifier.fillMaxWidth(),
        label = { Text("Email") },
        singleLine = true,
        isError = error != null,
        supportingText = { if (error != null) Text(error) },
        keyboardOptions = KeyboardOptions(
            keyboardType = KeyboardType.Email,
            imeAction = ImeAction.Next
        )
    )
}

The parameters you will use most:

  • label is a floating label that doubles as the placeholder; placeholder shows hint text only while the field is empty and focused.
  • isError draws the field in the error color; supportingText shows the explanation underneath. Show both, because color alone is not accessible.
  • leadingIcon / trailingIcon add icons, for example a clear button or a password visibility toggle.
  • singleLine = true keeps one line and turns the Enter key into an action key; maxLines and minLines control multi-line fields.
  • visualTransformation: PasswordVisualTransformation() shows dots. Toggle between it and VisualTransformation.None for a "show password" button.
  • readOnly and enabled control editing.

Keyboard options and actions

KeyboardOptions tells Android which keyboard to show. keyboardType can be Text, Email, Number, Phone, Password, Uri and others; capitalization and autoCorrectEnabled fine-tune typing; imeAction chooses the button at the keyboard's lower right corner: Next, Done, Go, Search, Send.

KeyboardActions says what happens when the user presses that button:

Kotlin
// read-only example: needs Compose and Material 3
@Composable
fun SignInForm(onSubmit: (String, String) -> Unit) {
    var email by rememberSaveable { mutableStateOf("") }
    var password by rememberSaveable { mutableStateOf("") }
    val focusManager = LocalFocusManager.current

    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
        OutlinedTextField(
            value = email,
            onValueChange = { email = it },
            label = { Text("Email") },
            singleLine = true,
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Email,
                imeAction = ImeAction.Next
            ),
            keyboardActions = KeyboardActions(
                onNext = { focusManager.moveFocus(FocusDirection.Down) }
            )
        )
        OutlinedTextField(
            value = password,
            onValueChange = { password = it },
            label = { Text("Password") },
            singleLine = true,
            visualTransformation = PasswordVisualTransformation(),
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Password,
                imeAction = ImeAction.Done
            ),
            keyboardActions = KeyboardActions(
                onDone = {
                    focusManager.clearFocus()
                    onSubmit(email, password)
                }
            )
        )
    }
}

By default, Next already moves focus to the next focusable element, so onNext is only needed to customize it. LocalFocusManager.current lets you move focus (moveFocus(FocusDirection.Down)) or dismiss the keyboard with clearFocus(). When you need to focus a specific field, for example the first invalid one after a failed submit, create a FocusRequester, attach it with Modifier.focusRequester(requester) and call requester.requestFocus() from an effect or click handler (see Side Effects for where such calls belong).

A good form follows a few conventions: the right keyboard type for each field, Next until the last field and Done on the last, and a visible way to submit that does not depend on the keyboard action alone. The autofill and password-manager support in Android works better when fields are labeled clearly and use the proper keyboardType.

The next TryIt models the focus and keyboard action logic in plain Kotlin. FormFocus knows the ordered list of fields. imeAction handles a keyboard button: Next moves focus down, Done tries to submit and only succeeds if every field has a value, which stands in for validation.

Kotlin Focus order and IME actions (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Validation as state

Where does validation belong? Not inside the TextField. Treat it as ordinary state logic: a function from the form values to a list of errors. Two questions then remain, when to show an error and where to keep the data.

A reliable approach is to track which fields are touched (the user has left them at least once), and show an error only for a touched field or after a submit attempt. Showing "Email is invalid" while the user is still typing the first character is rude.

stateDiagram-v2
    [*] --> Untouched
    Untouched --> Editing: user types
    Editing --> Touched: focus leaves
    Touched --> Editing: user types again
    Touched --> Valid: value passes checks
    Touched --> Invalid: value fails checks
    Valid --> Editing: user types again
    Invalid --> Editing: user types again

An error is shown only after a field has been touched (or the form submitted).

The second stand-in below implements the form as a reducer: events go in, a new immutable FormState comes out, and errors() is a pure function of the state. It is the same unidirectional shape the architecture chapter builds on, and it can be unit-tested without Compose.

Kotlin A form validation state machine (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Trace the first lines: typing "a" shows no error because the field is untouched; leaving it shows the error; fixing it clears it. The password error only appears after the first Submit, then goes away as the field becomes valid. In a real screen, state would live in a ViewModel and the composable would call viewModel.onEvent(Event.EmailChanged(it)).

Keep two other rules in mind. Client-side checks are for convenience: your server must validate again. And for server errors ("email already registered") put the message into state too, so it survives recomposition and rotation.

Checkboxes, switches and sliders

The other inputs follow the same value-in, event-out shape:

Kotlin
// read-only example: needs Compose and Material 3
@Composable
fun Preferences() {
    var agreed by rememberSaveable { mutableStateOf(false) }
    var notifications by rememberSaveable { mutableStateOf(true) }
    var volume by rememberSaveable { mutableFloatStateOf(0.5f) }

    Column {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .toggleable(
                    value = agreed,
                    role = Role.Checkbox,
                    onValueChange = { agreed = it }
                )
                .padding(vertical = 8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Checkbox(checked = agreed, onCheckedChange = null)
            Spacer(Modifier.width(8.dp))
            Text("I accept the terms")
        }

        Row(verticalAlignment = Alignment.CenterVertically) {
            Text("Notifications", modifier = Modifier.weight(1f))
            Switch(checked = notifications, onCheckedChange = { notifications = it })
        }

        Text("Volume: ${(volume * 100).toInt()}%")
        Slider(value = volume, onValueChange = { volume = it }, valueRange = 0f..1f, steps = 9)
    }
}
  • Checkbox(checked, onCheckedChange) is for choices that apply when you submit. Make the label tappable too: wrap the row in Modifier.toggleable (with onCheckedChange = null on the box itself) so the whole row is one touch target of at least 48dp, and TalkBack announces it as one control.
  • Switch is for settings that take effect immediately, like turning notifications on.
  • RadioButton with Modifier.selectable is for one-of-several choices.
  • Slider(value, onValueChange, valueRange, steps) picks a number in a range. steps is the count of stops between the ends (9 steps gives ten intervals); onValueChangeFinished fires when the user lifts their finger, which is the right place to save or call a network.

Putting it together

A solid form screen usually has these ingredients:

  1. A state class (or ViewModel state) holding the values, the touched set and any server error.
  2. Stateless field composables that take a value, an optional error and a change callback.
  3. The right KeyboardOptions and KeyboardActions per field, so users can finish without leaving the keyboard.
  4. One primary Button whose enabled state or error messages reflect validation.
  5. Scrolling (Modifier.verticalScroll) and Modifier.imePadding() so the keyboard never covers the field being edited. This depends on edge-to-edge insets, which Adaptive Layouts and Window Size Classes discusses.

The next lesson, Scaffold, App Bars, Dialogs and Snackbars, shows where such a form sits in a screen and how to report success or failure after submitting.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which button style should you use for the single most important action on a screen?

    The filled Button has the highest emphasis. Use it once per screen for the main action, and lower-emphasis styles for the rest.
  2. 2. What does ImeAction.Next set up?

    imeAction picks the button in the keyboard's corner. Next moves focus to the next focusable element; Done typically ends input. KeyboardActions defines what happens when it is pressed.
  3. 3. When should an error message normally appear for a text field?

    Showing errors while the user is still typing is frustrating. Tracking touched fields and a submit attempt shows errors at helpful moments; the server should still validate too.
  4. 4. Why wrap a Checkbox and its label in Modifier.toggleable?

    With toggleable on the row, tapping the label toggles the box, the touch target is large enough, and screen readers announce a single checkbox control.
  5. 5. Where does a TextField keep the text the user typed?

    TextField is stateless. It displays the value you give it and reports changes through onValueChange, so you own the text.

Summary

  • Choose among Button, FilledTonalButton, ElevatedButton, OutlinedButton and TextButton by emphasis; use enabled and explain why an action is unavailable.
  • TextField and OutlinedTextField are stateless: you hold the text and update it in onValueChange.
  • KeyboardOptions selects the keyboard and IME action; KeyboardActions defines what the action does; LocalFocusManager and FocusRequester control focus.
  • Model validation as a pure function of form state, plus touched fields and a submit flag, and show isError with supportingText.
  • Use Checkbox for submitted choices, Switch for immediate settings and Slider for ranges; make touch targets at least 48dp.
  • A reducer-based form state is easy to test without a device.
  • The Compose code here is read-only; the TryIt blocks are stand-ins for the form logic.

Next: Scaffold, App Bars, Dialogs and Snackbars