在activity中重写了dispatchKeyEvent事件,不论最后返回TRUE还是FALSE都不会执行onKeyDown事件了么?
找到的一些资料却不是这样解释的:
当键盘按下时
首先触发dispatchKeyEvent
然后触发onUserInteraction
再次onKeyDown
如果按下紧接着松开,则是俩步
紧跟着触发dispatchKeyEvent
然后触发onUserInteraction
再次onKeyUp
dispatchKeyEvent是做按键处理和分发的工作,如果你想要onKeyDown还可以接收到应该这样实现
public boolean dispatchKeyEvent(KeyEvent event){
return super.dispatchKeyEvent(event);
}
代码测试如下:
在dispatchKeyEvent(KeyEvent event)中按键的按下抬起都会进行操作,在处理完一个按键操作时无论return true 还是 false ,onKeyDown(int keyCode, KeyEvent event)和onKeyUp(int keyCode, KeyEvent event)都不会再进行按键处理:
第1种情况及log信息:
class="brush:csharp;gutter:true;">public void DEBUG(String str) { Log.d(TAG, str); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub DEBUG(" onKeyDown " + keyCode ); return super.onKeyDown(keyCode, event); } @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { // TODO Auto-generated method stub DEBUG(" onKeyLongPress " + keyCode ); return super.onKeyLongPress(keyCode, event); } @Override public boolean dispatchKeyEvent(KeyEvent event) { // TODO Auto-generated method stub DEBUG(" dispatchKeyEvent 1 key = " + event.getKeyCode() + " event = " + event.getAction()); if(event.getAction()==KeyEvent.ACTION_DOWN){ DEBUG(" dispatchKeyEvent 2 ACTION_DOWN" + event.getKeyCode() ); return super.dispatchKeyEvent(event); } if(event.getAction()==KeyEvent.ACTION_UP){ DEBUG(" dispatchKeyEvent 3 ACTION_UP" + event.getKeyCode() ); return super.dispatchKeyEvent(event); } return super.dispatchKeyEvent(event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { // TODO Auto-generated method stub DEBUG(" onKeyUp " + keyCode); return super.onKeyUp(keyCode, event); }log信息:
D/ testMainActivity ( 853): dispatchKeyEvent 1 key = 23 event = 0
D/ testMainActivity ( 853): dispatchKeyEvent 2 ACTION_DOWN23
D/ testMainActivity ( 853): onKeyDown 23
D/ testMainActivity ( 853): dispatchKeyEvent 1 key = 23 event = 1
D/ testMainActivity ( 853): dispatchKeyEvent 3 ACTION_UP23
D/ testMainActivity ( 853): onKeyUp 23