I am making a program with a lot of text fields that needs to shift focus once Enter is pressed. They are all set to single line. (It should go to the next text field, once Enter is pressed)
I was using a focus requester, but it turns out in windows this is not necessary. Removing it, I still was able to change focus with tab. Is there a way to make this work with Enter?
CodePudding user response:
It works out of the box because all text fields are focusable by default. Read more about the topic in Tabbing navigation and keyboard focus.
You can use LocalFocusManager
to move focus with custom events:
val focusManager = LocalFocusManager.current
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxSize()
.onKeyEvent {
if (it.key == Key.Enter && it.type == KeyEventType.KeyDown) {
focusManager.moveFocus(FocusDirection.Next)
true
} else {
false
}
}
) {
Column(
modifier = Modifier.padding(50.dp)
) {
for (x in 1..5) {
val text = remember { mutableStateOf("") }
OutlinedTextField(
value = text.value,
singleLine = true,
onValueChange = { text.value = it }
)
Spacer(modifier = Modifier.height(20.dp))
}
}
}