项目开发中涉及到按键事件处理:
“dispatchKeyEvent” “onKeyDown ”“onKeyLisenter” 简单理解
咨询同事,告知其接受按键优先级:
dispatchKeyEvent > Activity的onKeyDown > view的onKeyLisenter
其中按键处理事件return true ;表示已消耗此事件,不再继续传递;
1. dispatchKeyEvent 事件
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_LEFT :
break;
case KeyEvent.KEYCODE_DPAD_RIGHT :
break;
default :
break;
}
}
return ret ? true : super.dispatchKeyEvent(event);
}
2.onkeyDown 事件
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
return super.onKeyDown(keyCode, event);
}
3. onKeyLisenter 事件
3.1 Activity 或者 Fragment 类需要继承接口implements OnKeyListener
3.2 view 也需要注册事件:
view.setOnkeyListener(context);
3.3 继承接口,实现内部未实现的方法
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_UP :
break;
case KeyEvent.KEYCODE_DPAD_DOWN :
break;
case KeyEvent.KEYCODE_DPAD_LEFT :
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
break;
default :
break;
}
}
return false;
}
网友评论