Android jetpack compose: Navigate through text fields

Viewed 228

I implemented a screen that has a lot of TextFields and I used the scaffold as a root layer. Because I wanted my screen to be rtl, I used Composition Local provider().

CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl ) {}

My TextFields were on the screen like this:

B A

D C

and when I wanted to navigate through these TextFields:

keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(
      onNext = { LocalFocusManager.current.moveFocus(FocusDirection.Next) }
)

what I Expected to happend: A -> B -> C -> D

what happend: B -> A -> D -> C

(I used a Column for parent root but textfields have Row as Parent root two by two (the Rows are in Column))

Can anyone help? Thanks.

1 Answers

You can use .focusOrder modifier to achieve this:

Column() {
    val (aFocus, bFocus, cFocus, dFocus) = remember { FocusRequester.createRefs() }


    Row {
        OutlinedTextField(
            value = "A",
            onValueChange = {},
            modifier = Modifier
                .weight(1f)
                .focusOrder(aFocus) { next = bFocus },
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
        )
        OutlinedTextField(
            value = "B",
            onValueChange = {},
            modifier = Modifier
                .weight(1f)
                .focusOrder(bFocus) { next = cFocus },
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next)
        )
    }

    Row {
        OutlinedTextField(
            value = "C",
            onValueChange = {},
            modifier = Modifier
                .weight(1f)
                .focusOrder(cFocus) { next = dFocus },
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next)
        )
        OutlinedTextField(
            value = "D",
            onValueChange = {},
            modifier = Modifier
                .weight(1f)
                .focusOrder(dFocus) { },
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next)
        )
    }
}

Related