Android: How to ignore control key input from external keyboard in textfields using jetpack compose

Viewed 41

I am entering the password field values from devices with physical keyboards (like the emulator and ChromeOS). I need to ignore when the user presses TAB or ENTER (or other special) keys, so that it is not entered directly into the text.

I would like to match the behavior of a standard AlertDialog password prompt, where pressing Enter on the physical keyboard submits the password. So, is there any better way to ignore control keys?

2 Answers

Not sure if this would work on an external keyboard, but have you tried doing something like this?

TextField (
        modifier = Modifier
            .onKeyEvent {
                if (it.key == Key.Tab || it.key == Key.Enter) {
                    // do want you want here
                    false // or true based on your use-case
                } else {
                    
                    true // or false based on your use-case
                }
            }

just a warning Key is under an experimental API @OptIn(ExperimentalComposeUiApi::class)

Use combination of Regex and onKeyEvent.

fun TestTextField() {
    val scope = rememberCoroutineScope()
    val (value, onValueChange) = remember() {
        mutableStateOf("")
    }
    val passwordRegex by rememberSaveable() {
        //this regex allows digits, and *#w+ only. Use your own regex.
        mutableStateOf(Regex("^[0-9*#w+]+$"))
    }

    fun submitPassword() {
        scope.launch {
            //do what you want
        }
    }
    TextField(
            modifier = Modifier.onKeyEvent {
                if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_ENTER) {
                    submitPassword()
                }
                return@onKeyEvent false
            },
            value = value,
            onValueChange = {
                if (!it.matches(passwordRegex)) {
                    return@TextField
                }
                onValueChange(it)
            }
    )
}
Related