一、背景
Activity和View有三个override的方法dispatchKeyEvent、onKeyUp、onKeyDown,其中View还有一个setOnKeyListener方法。只知道这几个方法是设置处理key event的,但是一直不太理解这几个方法的作用和相互影响。所以准备写个demo彻底搞清楚这几个方法的作用和原理。
二、测试准备
新建三个类
public class KeyDispatchDemo extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_key_dispatch);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
Log.d("Activity", "dispatchKeyEvent: " + event.getAction() + " | " + event.getKeyCode());
return super.dispatchKeyEvent(event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
Log.d("Activity", "onKeyUp: " + keyCode);
return super.onKeyUp(keyCode, event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.d("Activity", "onKeyDown: " + keyCode);
return super.onKeyDown(keyCode, event);
}
}
public class KeyDispatchLinearLayout extends LinearLayout {
public KeyDispatchLinearLayout(Context context) {
super(context);
}
pub