5

I am trying to execute a function upon Enter Key pressed on soft keyboard and I found Modifier.onKeyEvent{} to listen to user input on soft keyboard in general.

However, this doesn't work with Enter key(especially 'Done' key on number pad).

My soft keyboard looks like this

enter image description here

with this option below in TextField

keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number)

when I print logs on any key pressed, all other keys press are recognized but those 'Done' and '.-' keys.

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
foseja
  • 233
  • 2
  • 10

2 Answers2

4

You can handle it with keyboardActions text field argument:

TextField(
    value = text, onValueChange = { text = it },
    keyboardOptions = KeyboardOptions.Default.copy(
        keyboardType = KeyboardType.Number,
        imeAction = ImeAction.Done
    ),
    keyboardActions = KeyboardActions(onDone = {
        println("done")
    })
)
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
  • Thank you so much, you saved my day. but I am just curious where you got this solution? I wasn't able to find it anywhere. could you leave me a link related to this? – foseja Sep 30 '21 at 18:41
  • @foseja I've added link to documentation. Also you can check out [this article](https://betterprogramming.pub/android-keyboard-handling-using-jetpack-compose-c478f7afaae0) – Phil Dukhov Sep 30 '21 at 18:46
1

The enter key is special. Especially when it's not an enter key, but a Done button or similar. Instead of sending a commitText, it send it via the OnEditorActionListener of the view. You need to set an OnEditorActionListener and handle the case in that.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127