事件分发机制:某一个事件从屏幕传递至各个view,由view来使用这一事件(消费事件)或者忽略这一事件(不消费事件),这整个过程的控制。
系统把事件封装为MotionEvent对象(ACTION_DOWN、ACTION_MOVE、ACTION_UP、ACTION_CANCEL ),事件分发的过程就是MotionEvent分发的过程。
传递层级:Activityà Windowà DecorViewà ViewGroupà View
Activity中分发用到的两个方法:
dispatchTouchEvent(MotionEvent ev)
onTouchEvent(MotionEvent event)
Activity.dispatchTouchEvent方法
进入getWindow().superDispatchTouchEvent(ev),可以发现该方法是一个抽象方法。
该抽象类的实现在phoneWindow中:
每一个Activity都持有一个window对象,而window本身是一个抽象类,他有一个唯一的实现,就是PhoneWindow。对于PhoneWindow来说,他持有一个DecorView的实例,DecorView就是Activity最顶层的view,在Activity的onCreate()方法中setContentView(Layout)的时候就是把这个传入的layout添加进了DecorView中。
跟踪上面代码,进入DecorView的superDispatchTouchEvent()中:
可以看见DecorView是直接调用了他父类的DispatchTouchEvent(). DecorView的父类是FrameLayout(FrameLayout的父类是ViewGroup)。而FrameLayout本身是没有DispatchTouchEvent()方法的,他方法的实现就是在ViewGroup中。由此从Activity中发生的事件就分发到了ViewGroup中。
当Activity中getWindow().superDispatchTouchEvent(ev)返回false时,会调用Activity的onTouchEvent方法。
其中:
mCloseOnTouchOutside为true的时候,表示当前Activity支持点击空白部分让Activity进行消失;peekDecorView!=null代表当前PhoneWindow下持有DecorView;当isOutside为true时,表示当前的事件是在DecorView之外的。
ViewGroup中分发用到的三个方法:
dispatchTouchEvent(MotionEvent ev):
·去判断是否需要拦截事件;
·在当前ViewGroup中找到用户真正点击的View;
·分发事件到view上;
onInterceptTouchEvent(MotionEvent ev)
onTouchEvent(MotionEvent event)
其中:
判断当前事件是否符合安全策略。当前view不是与用户直接交互,且这个view不在顶部时不响应这个触摸事件的话,该方法返回false。
ViewGroup.onInterceptTouchEvent(MotionEvent ev):
dispatchTouchEvent(MotionEvent ev):
View分发用到的三个方法:
dispatchTouchEvent(MotionEvent ev):
onTouchEvent(MotionEvent event)
View.dispatchTouchEvent(MotionEvent ev):
View.onTouchEvent(MotionEvent ev):