在ViewGroup里覆写了onInterceptTouchEvent()方法,就能够对各类touch事件加以拦截。可是touch事件在onInterceptTouchEvent()和onTouchEvent以及各个childView间的传递机制彻底取决于onInterceptTouchEvent()和onTouchEvent()的返回值。java
down事件首先会传递到onInterceptTouchEvent()方法。该ViewGroup的onInterceptTouchEvent()在接收到down事件处理完成以后:android
(1)return false,那么后续的move, up等事件将继续会先传递给该ViewGroup,以后才和down事件同样传递给最终的目标view的onTouchEvent()处理。spa
(2)return true,那么后续的move, up等事件将再也不传递给onInterceptTouchEvent(),而是和down事件同样传递给该ViewGroup的onTouchEvent()处理,注意,目标view将接收不到任何事件。 code
若是最终须要处理事件的view的onTouchEvent()返回了false,那么该事件将被传递至其上一层次的view的onTouchEvent()处理。 orm
若是最终须要处理事件的view 的onTouchEvent()返回了true,那么后续事件将能够继续传递给该view的onTouchEvent()处理。xml
实验:事件
<?xml version="1.0" encoding="utf-8"?> <com.test.LayoutView1 xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <com.test.LayoutView2 android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center"> <com.test.MyTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="AB"/> </com.touchstudy.LayoutView2> </com.touchstudy.LayoutView1>
onInterceptTouchEvent()处理down事件均返回false,onTouchEvent处理事件均返回true:
utf-8
LayoutView1 : onInterceptTouchEvent action : ACTION_DOWNit
LayoutView2 : onInterceptTouchEvent action : ACTION_DOWNio
MyTextView : onTouchEvent action : ACTION_DOWN
LayoutView1 : onInterceptTouchEvent action : ACTION_MOVE
LayoutView2 : onInterceptTouchEvent action : ACTION_MOVE
MyTextView : onTouchEvent action : ACTION_MOVE
这是最多见的状况,onInterceptTouchEvent并无作任何改变事件传递时序的操做,效果上和没有重写该方法同样。各类事件的传递自己是自底向上的,次序:LayoutView1 -> LayoutView2 -> MyTextView. 在onInterceptTouchEvent均返回false时,LayoutView1 和 LayoutView2 的onTouchEvent并不会接收到事件,而是最终传递给了MyTextView.
LayoutView1 的onInterceptTouchEvent处理down事件返回true,MyTextView的onTouchEvent事件返回true:
LayoutView1 : onInterceptTouchEvent action : ACTION_DOWN
LayoutView1 : onTouchEvent action : ACTION_DOWN
LayoutView1 : onTouchEvent action : ACTION_MOVE
LayoutView1 : onTouchEvent action : ACTION_MOVE
LayoutView1 : onTouchEvent action : ACTION_UP
LayoutView1在拦截第一次down事件时return true,因此后续事件(包括第一次的down)将由LayoutView1自己处理,事件再也不传递下去。
LayoutView1,LayoutView2的onInterceptTouchEvent处理down事件返回false,MyTextView的onTouchEvent事件返回false,LayoutView2的onTouchEvent事件返回true
LayoutView1 : onInterceptTouchEvent action : ACTION_DOWN
LayoutView2 : onInterceptTouchEvent action : ACTION_DOWN
MyTextView : onTouchEvent action : ACTION_DOWN
LayoutView2 : onTouchEvent action : ACTION_DOWN
LayoutView1 : onInterceptTouchEvent action : ACTION_MOVE
LayoutView2 : onTouchEvent action : ACTION_MOVE
LayoutView1 : onInterceptTouchEvent action : ACTION_MOVE
LayoutView2 : onTouchEvent action : ACTION_MOVE