Android physical keyboard event resolution
•
Android
preface
Connecting Android devices to physical keyboards is actually a small demand. In fact, Android devices support physical keyboards. The dispatchkeyevent() method can monitor physical keyboards. Here, an encapsulated class is provided to parse keyboard events. There are many events. You can see the source code of keyevent class. I only deal with the numeric keypad here.
Implementation mode
1. Keyboard event parsing class
public class DispatchKeyResolver { public OnKeyInputListener keyInputListener; public void resolveKeyEvent(KeyEvent event) { getInputChar(event); } public void getInputChar(KeyEvent event) { int keyCode = event.getKeyCode(); char aChar; if(keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9) { //数字 aChar = (char) ('0' + keyCode - KeyEvent.KEYCODE_0); } else if(keyCode >= KeyEvent.KEYCODE_NUMPAD_0 && keyCode <= KeyEvent.KEYCODE_NUMPAD_9) { //数字 aChar = (char) ('0' + keyCode - KeyEvent.KEYCODE_NUMPAD_0); } else { //其他符号 switch(keyCode) { case KeyEvent.KEYCODE_PERIOD: aChar = '.'; break; case KeyEvent.KEYCODE_NUMPAD_DOT: aChar = '.'; break; default: return; } } keyInputListener.onKeyInput(aChar); } public void setKeyInputListener(OnKeyInputListener keyInputListener) { this.keyInputListener = keyInputListener; } public interface OnKeyInputListener { void onKeyInput(char aChar); } }
2. Set listening
DispatchKeyResolver dr = new DispatchKeyResolver(); //设置事件回调 dr.setKeyInputListener(...) @Override public boolean dispatchKeyEvent(KeyEvent event) { //物理键确定,并且是按下的行为(避免两次响应) if(event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN){ dr.resolveKeyEvent(event) } return super.dispatchKeyEvent(event); }
The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码