android 中Activity跟View对于键盘的监听,主要有以下几个方法
//按键按下 public boolean onKeyDown(int keyCode, KeyEvent event) {} //按键弹起 public boolean onKeyUp(int keyCode, KeyEvent event) {} //常按 public boolean onKeyLongPress(int keyCode, KeyEvent event) {}
我们今天先看的就是按下、弹起两个事件,在activity跟view两者之间的传递关系。
我们先看如下的测试代码
首先是自定义view,重写了onkeyDown 跟onkeyUp两个方法
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub boolean a = super.onKeyDown(keyCode, event); Log.e("123", "view_onkeydown|a===" + a); return a; } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { // TODO Auto-generated method stub boolean a = super.onKeyUp(keyCode, event); Log.e("123", "view_onkeyup|a==" + a); return a; }
接下来是在activity中重写了上面两个方法
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub Log.e("123", "activity_onkeydown"); return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { // TODO Auto-generated method stub Log.e("123", "activity_onkeyup"); return super.onKeyUp(keyCode, event); }
然后我们打下log
1.当焦点不在自定义view上的时候
1 00-01 08:59:54.755: E/123(9250): activity_onkeydown 2 01-01 08:59:54.951: E/123(9250): activity_onkeyup 3 01-01 08:59:55.757: E/123(9250): activity_onkeydown 4 01-01 08:59:55.964: E/123(9250): activity_onkeyup
2.当焦点在view上的时候
1 01-01 09:01:14.914: E/123(9250): view_onkeydown|a===true 2 01-01 09:01:15.043: E/123(9250): view_onkeyup|a==false 3 01-01 09:01:15.044: E/123(9250): activity_onkeyup 4 01-01 09:01:16.451: E/123(9250): view_onkeydown|a===true 5 01-01 09:01:16.614: E/123(9250): view_onkeyup|a==false 6 01-01 09:01:16.615: E/123(9250): activity_onkeyup
总结:
从上面的log结果,我们能得到以下两个知识点
1.控件对键盘的监听,只有当控件获得焦点的时候,才能够起效果,activity对控件的监听是一直存在的
2.如果控件获得了焦点,那么监听顺序是,先view,后activity
3.如果view返回为ture,那么activity相应的监听就不会接受到按键事件