androidkotlinandroid-jetpack-composetextfieldandroid-compose-textfield

Jetpack Compose TextField capture keyboard Enter-input


From what I understand, there is an API for the Jetpack Compose Textfield for capturing Keyboard actions but I don't know what of this APIs that can capture the Enter-Input

The use-case of this capturing enter input is to enable to click Enter and try to go to the next TextField and keeping while keeping the keyboard open

OutlinedTextField(
    value = username.value,
    onValueChange = {
        username.value = it
        },
    keyboardActions = KeyboardActions(
        onDone = {},
        onGo = {},
        onNext = {},
        onPrevious ={},
        onSearch ={},
        onSend = {}
        )
)

Solution

  • You can use something like:

    val (focusRequester) = FocusRequester.createRefs()
    
    TextField(
        value = text,
        onValueChange = {
            text = it
        },
        singleLine = true,
        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
        keyboardActions = KeyboardActions(
            onDone = { focusRequester.requestFocus() }
        ),
        modifier = Modifier.onKeyEvent {
            if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_ENTER){
                focusRequester.requestFocus()
                true
            }
            false
        }
    )
    
    TextField(
        value = text2,
        onValueChange = {
            text2 = it
        },
        modifier = Modifier.focusRequester(focusRequester),
    )