安卓中滑动事件的传递机制及dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent的调用

在探讨Android事件传递机制前,明确android的两大基础控件类型:ViewViewGroup,另外还有Activity,View即普通的控件,没有子布局的,如Button、TextView. ViewGroup继承自View,表示可以有子控件,如Linearlayout、Listview这些。而事件即MotionEvent,最重要的有3个:
(1)MotionEvent.ACTION_DOWN  按下View,是所有事件的开始
(2)MotionEvent.ACTION_MOVE   滑动事件
(3)MotionEvent.ACTION_UP       与down对应,表示抬起

对于View来说,事件传递机制只有一个函数:onTouchEvent表示执行事件,或者说消费事件,事件传递的入口是ActivitydispatchTouchEvent函数.

对于Activity来说,事件传递机制有两个函数:dispatchTouchEvent负责分发事件,onTouchEvent表示消费事件,在dispatchTouchEvent里又会调用onTouchEvent表示消费事件.

再来看ViewGroup,在复写ViewGroup时可以发现它的onTouchEvent,dispatchTouchEvent两个方法跟Activity是一样的,多了一个onInterceptTouchEvent函数,表示拦截的意思。为啥View没有呢,因为它级别不够,一个Button里面是不可能有子View的。但LinearLayout(继承ViewGroup)就有孩子(子布局),这个onInterceptTouchEvent就会判断事件要不要通知它的孩子呢。

总结:
(1)不管是 View 还是 ViewGroup 事件入口都是ActivitydispatchTouchEvent(MotionEvent ev),默认返回super.dispatchTouchEvent(ev),若子控件是ViewGroup即继续往下传给自己的 onInterceptTouchEvent(MotionEvent ev)方法,返回 true 或 false 则表示终止事件传递。如果返回true则表示自己消费掉,事件不会往上或往下传递,如果返回false则表示自己不处理返回给父类的onTouchEvent方法处理.

(2)对于onInterceptTouchEvent(MotionEvent ev)来说,如果返回 true,则表示终止事件向子 View 或子 ViewGroup 传递,即传递给自己的onTouchEvent(MotionEvent ev)方法中消费掉事件。如果返回false或 super.onInterceptTouchEvent(ev),则表示事件传递给子 View 或子ViewGroup的dispatchTouchEvent(MotionEvent ev)方法,在子View或dispatchTouchEvent(MotionEvent ev)方法中判断依刚才(1)点所说。
(3)对于onTouchEvent(MotionEvent ev)来说,子 View 或 ViewGroup 的onTouchEvent(MotionEvent ev)如果返回 true 这表示自己消费掉处理事件,返回false或 super.onTouchEvent(ev),则表示把事件返回给父类中的onTouchEvent(MotionEvent ev)方法来处理。


猜你喜欢

转载自blog.csdn.net/qq_34581102/article/details/51972001