[SOLVED] Android: enter or tab keys still enters values into the password input field using jetpack compose

Issue

This Content is from Stack Overflow. Question asked by kgsharathkumar

When I enter or tab keys still enters values into the password input field using jetpack compose.

Below is my code snippet:

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
    }
)

Tab key and enter key entries from laptop keyboard via Vysor not from android keyboard.

Any suggestions are welcome here. Thanks!



Solution

You can use a regex, something like:

 val pattern = remember { Regex("^[^\\t\\n]*\$") }
 val focusManager = LocalFocusManager.current

 TextField(
        value = text,
        onValueChange = {
            if (it.isEmpty() || it.matches(pattern)) {
                text = it
            }
        },
        singleLine = true,
        maxLines= 1,
                    keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
        keyboardActions = KeyboardActions(
            onDone = { focusManager.moveFocus(FocusDirection.Next) }
        ),
        modifier = Modifier.onKeyEvent {
            if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_ENTER || it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_TAB) {
                focusManager.moveFocus(FocusDirection.Next)
            }
            false
        }
   )


This Question was asked in StackOverflow by kgsharathkumar and Answered by Gabriele Mariotti It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?