一.按键事件处理,事件传递模型
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } //按键按下的时候; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { Log.e("---------","onKeyDown"); return super.onKeyDown(keyCode, event); } //按键松开 @Override public boolean onKeyUp(int keyCode, KeyEvent event) { Log.e("---------","onKeyUp"); return super.onKeyUp(keyCode, event); } //按键长按的时候; @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { Log.e("---------","onKeyLongPress"); return super.onKeyLongPress(keyCode, event); }}
如果按下返回键的时候:
onKeyDown--->onKeyUp
源码分析:
Activity: onKeyDown()
event.startTracking();//计数
Activity:对于我们回退键的处理: down:计数 up:判断是否计数过 如果计数过 那么就退出
return false: 就是应用层没有处理了事件,继续传递.-->相应给驱动层
return true:就表示事件,就意味着不向系统响应
长按键 是如何发生的呢
event.startTracking();//计数
return true//拦截事件
home键是一个敏感键,是交给系统层处理的,应用层是不可以处理的,
二.触摸事件处理,事件传递模型
触摸事件的类型
:down
:up
:move
:pointer_down 多指事件
public class MainActivity extends Activity implements OnTouchListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv = (TextView) findViewById(R.id.tv); tv.setOnTouchListener(this); LinearLayout ll = (LinearLayout) findViewById(R.id.ll); MyTouchEvent event = new MyTouchEvent(); ll.setOnTouchListener(event); } private class MyTouchEvent implements OnTouchListener{ @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: Log.i("tz","layout down"); break; case MotionEvent.ACTION_MOVE: Log.i("tz","layout move"); break; case MotionEvent.ACTION_UP: Log.i("tz","layout up"); break; } return true; } } /** * 触摸事件:down move up pointer_down多指 */ @Override public boolean onTouch(View v, MotionEvent event) { int count = event.getPointerCount(); //获得触摸手指的数量 switch (event.getAction()) { case MotionEvent.ACTION_DOWN: Log.i("tz","down"); //拿到按下的坐标 float x = event.getX(); float y = event.getY(); x = event.getRawX();//以屏幕为坐标系 包括了标题栏和状态栏的坐标 y = event.getRawY(); Log.i("tz", "RawX:"+x); Log.i("tz","RawY:"+y); break; case MotionEvent.ACTION_POINTER_DOWN://多跟手指按下 Log.i("tz","pointer_down"); //获取第2根手指的坐标??获取第3根手指的坐标?? x = event.getX(count-1);//下标从0开始 y = event.getY(count-1); break; case MotionEvent.ACTION_MOVE: Log.i("tz","move"); x = event.getX();//以我们点击的view为坐标 y = event.getY(); x = event.getRawX();//以屏幕为坐标系 y = event.getRawY(); //其他手指移动的坐标 x = event.getX(count-1); y = event.getY(count-1); Log.i("tz", "move RawX:"+x); Log.i("tz","move RawX:"+y); break; case MotionEvent.ACTION_UP: Log.i("tz","up"); break; } return true;//表示将事件拦截(消费) //return false;//表示事件交由上级容器处理 move up 就捕获不到了 //return super.onTouchEvent(event);//把事件交给Activity处理 由Activity类决定是return true 还是false; }}
如果在down的时候,农民没有完成任务,以后市长秘书就不会叫农民处理move和up事件了