前言
Android设备连接物理键盘其实是个挺小众的需求,其实Android设备本身就是支持物理键盘,dispatchKeyEvent()这个方法就可以监听物理键盘,这里提供一个封装的类,解析键盘事件。有很多事件,具体可以去看KeyEvent这个类的源码,我这里只处理的数字键盘。
实现方式
1.键盘事件解析类
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.设置监听
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); }