内容来自:
安卓自定义View进阶-事件分发机制原理Android事件传递机制分析Understanding Android touch flow control事件分发、拦截、消费涉及到的方法
类型相关方法ActivityViewGroupView事件分发dispatchTouchEvent√√√事件拦截onInterceptTouchEventX√X事件消费onTouchEvent√√√dispatchTouchEvent 方法
Pass the touch screen motion event down to the target view, or this view if it is the target. 将事件向下传递到目标view 返回值:True if the event was handled by the view, false otherwise. true表示事件被view处理了,false则反之
onInterceptTouchEvent方法拦截所有的触摸屏幕的motion event。
onTouchEvent方法会处理motion event
从上表可看出Activity 和 View 都是没有事件拦截
事件分发流程
当发生触摸,先从Activity开始,然后向下传递到layout,然后到layout上的view
这样做的目的是找到第一个对touch感兴趣的对象。找到之后,任务就结束了。如果大家都不感兴趣,就会被丢弃
整个流程大概类似于,father得到了个apple,然后传递给大儿子,然后再传递给弟弟
如果弟弟对这个apple不感兴趣,他就把这个apple传递给哥哥。如果哥哥也不感兴趣,就再传递给father。
在Manage touch events in a ViewGroup有这样的描述:
The onInterceptTouchEvent() method is called whenever a touch event is detected on the surface of a ViewGroup, including on the surface of its children. If onInterceptTouchEvent() returns true, the MotionEvent is intercepted, meaning it is not passed on to the child, but rather to the onTouchEvent() method of the parent.
如果 onInterceptTouchEvent() r返回true,则 MotionEvent被拦截,意味着它不会传递到child上,而是传递到父view的onTouchEvent()