How do I create a form like this which can have th...
# compose
c
How do I create a form like this which can have the keyboard go to the next text field, and on the second text field, the keyboard essentially clicks the button?
My code (wrapped in a column):
Copy code
var first by remember { mutableStateOf("") }
var last by remember { mutableStateOf("") }

TextField(
    value = first,
    onValueChange = { first = it },
    label = { Text("First name") }) //<==== Should have a next button that focuses next textField

TextField(
    value = last,
    onValueChange = { last = it },
    label = { Text("Last name") }) //<==== Should have a done button that triggers the button below

Button({ /*Do something */}) {}
Is there an easy way to just set a column as being a form and to keep going to the next field?
l
You can use FocusManager to move focus to the next text field, and then just submit on ime action
1
Copy code
TextField(
            value = uiState.email,
            onValueChange = viewModel::updateEmail,
            placeholder = { Text("Email") },
            singleLine = true,
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
            keyboardActions = KeyboardActions(
                onNext = { focusManager.moveFocus(FocusDirection.Down) }
            ),
            modifier = Modifier.fillMaxWidth()
        )

        TextField(
            value = uiState.password,
            onValueChange = viewModel::updatePassword,
            placeholder = { Text("Password") },
            singleLine = true,
            keyboardActions = KeyboardActions(
                onDone = { viewModel.login() }
            ),
            modifier = Modifier.fillMaxWidth()
        )
I have those two fields in my project, email and password text fields. The
onDone
keyboard action for the password just calls the same method the button would call
c
Where do I get a "focusManager"? Is it typical to just create one for the entire screen or per composable?
l
You have a
LocalFocusManager
that you can use,
val focusManager = LocalFocusManager.current
c
Got it. Works great! Thank you! Need to come up with a gameplan for how this could work for dynamically sized forms (the app I'm building is similar to google forms), and then I need to also try to wire this in with the enter key and tab key when using an actual keyboard.
If anyone wants more docs/samples on focus, please star https://issuetracker.google.com/issues/200374698