I have an activity with a set of buttons on it, it resembles a NumPad keyboard.
My purpose: to do some terminal for input data with help of little (hard) “usb NumPad keyboard” – so interface looks as NumPad – just a set of Buttons.
I want to handle all the keyboard events to do with them what I need to do (my own function for each button). Overrided functions onKeyUp and onKeyDown – and they do all that I need, except handling the Enter key. In these two functions it’s not an event at all as I see.
On Enter activity opens menu, so Enter is some special function – not for me, but for system.
All the topics here that I saw (how to handle “Enter”) are about soft keyboard or EditView. I don’t have on my activity any editable, I just want to catch Enter event, or maybe possible link Enter with some of the Buttons on activity.
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
Toast.makeText(this,keyCode.toString(),Toast.LENGTH_SHORT).show()
val res: Int = when (keyCode) {
KeyEvent.KEYCODE_NUMPAD_0 -> 0
KeyEvent.KEYCODE_0 -> 0
KeyEvent.KEYCODE_NUMPAD_1 -> 1
KeyEvent.KEYCODE_1 -> 1
KeyEvent.KEYCODE_DPAD_DOWN_LEFT -> 1
KeyEvent.KEYCODE_NUMPAD_DOT -> 10
KeyEvent.KEYCODE_NUM_LOCK -> 11
KeyEvent.KEYCODE_NUMPAD_ENTER -> 16 //never happens
else -> -1
}
if (res>=0) doAction(res)
return if (res == -1) super.onKeyUp(keyCode, event)
else true
}
Use dispatchKeyEvent to handle enter:
override fun dispatchKeyEvent(event:KeyEvent):Boolean {
if (event.getAction() === KeyEvent.ACTION_UP)
{
Toast.makeText(this,event.getKeyCode().toString(),Toast.LENGTH_SHORT).show()
return true
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With