事件分发机制的作用
试想一下,界面中有两个button,小的按钮覆盖在大的上面,两个按钮都设置了点击事件,此时点击面积小的按钮,怎么处理让哪个按钮响应点击事件呢?答案是事件分发
Android上事件分发是怎么实现的
Android上的事件由MotionEvent表示,其中存在ACTION_DOWN,ACTION_MOVE,ACTION_UP,分别代表按下,移动,抬起操作。
涉及到的对象:Activity,PhoneWindow,ViewGroup,View这些对象之间进行分发传递
涉及到的方法: onTouchEvent,dispatchTouchEvent,onInterceptorTouchEvent
源码:Activity::dispatchTouchEvent
/**
* Called to process touch screen events. You can override this to
* intercept all touch screen events before they are dispatched to the
* window. Be sure to call this implementation for touch screen events
* that should be handled normally.
*
* @param ev The touch screen event.
*
* @return boolean Return true if this event was consumed.
*/
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
Activity中的dispatchTouchEvent方法,表示触摸事件被处理,我们可以通过重写此方法来阻止所有的事件被传递到window,但是为了屏幕时间可以被正常处理,需要确保调用了该实现
ev参数表示一个触摸事件
boolean 返回值表示事件是否被消费
Window,Activity,DecorView布局图