Android capture hardware keyboard event without edittext view

◇◆丶佛笑我妖孽 提交于 2019-12-12 08:07:53

问题


How can I capture the hardware keyboard events without using an EditText field?

For example, in a simple activity the display a square on the screen, when a "B" is pressed on the slide keyboard I want to turn it blue, when a "G" is presses, turn it Green, etc.

I don't need help with the color code, just how to intercept the keypress

This is not about the soft or virtual keyboard


回答1:


Android classes usually provide event handlers, you can implement when subclassing them. The Activity class has the following event handlers:

  • onKeyDown(int keyCode, KeyEvent event)
  • onKeyLongPress(int keyCode, KeyEvent event)
  • onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
  • onKeyShortcut(int keyCode, KeyEvent event)
  • onKeyUp(int keyCode, KeyEvent event)

In addition all views have the following event handlers:

  • onKeyDown(int, KeyEvent)
  • onKeyUp(int, KeyEvent)

I guess there are many other classes that have similar event handlers for key events, but this should be enough for your situation. The KeyEvent then contains information about the pressed key, i.e. the key code.




回答2:


Activity class has already implemented KeyEvent.CallBack see here

you just need to override these methods and implements all events that you want



来源:https://stackoverflow.com/questions/5296507/android-capture-hardware-keyboard-event-without-edittext-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!