关闭

Android6.0 ViewGroup/View 事件分发机制详解

72人阅读 评论(0) 收藏 举报
分类:

之前自认为对于Android的事件分发机制还算比较了解,直到前一阵偶然跟人探讨该问题,才发现自己以前的理解有误,惭愧之余遂决定研习源码,彻底弄明白Android的事件分发机制,好了废话少说,直接开干。

首先,我们对Android中的touch事件做一下总结,主要分为以下几类:

1、Action_Down  用户手指触碰到屏幕的那一刻,会触发该事件;

2、Action_Move   在触碰到屏幕之后,手指开始在屏幕上滑动,会触发Action_Move事件;

3、Action_Up       在用户手指从屏幕上离开那一刻开始,会触发Action_Up事件;

4、Action_Cancel Cancel事件一般跟Up事件的处理是一样的,是由系统代码自己去触发,比如子view的事件被父view给拦截了,之前被分发的子view就会被发送cancel事件,或者用户手指在滑动过程中移出了边界。另外,在有多点触控事件时,还会陆续触发ACTION_POINTER_DOWN、ACTION_POINTER_UP等事件。

其次,我们知道Android中负责事件分发机制的方法主要有以下三个:

1、dispatchTouchEvent(MotionEvent event) — 分发事件

      我们知道当用户触摸到手机屏幕时,最先接收到事件并进行相应处理的应该是最外层的Activity,所以我们来看看Activity中是如何对事件进行分发的。

  1. public boolean dispatchTouchEvent(MotionEvent ev) {  
  2.     if (ev.getAction() == MotionEvent.ACTION_DOWN) {  
  3.         onUserInteraction();  
  4.     }  
  5.     if (getWindow().superDispatchTouchEvent(ev)) {  
  6.         return true;  
  7.     }  
  8.     return onTouchEvent(ev);  
  9. }  
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
        从以上代码中我们可以看到调用getWindow().superDispatchTouchEvent(),而这里的getWindow()返回的是Window抽象类,其实就是PhoneWindow类,继承于Window抽象类,然后调用PhoneWindow的superDispatchTouchEvent(),

  1. @Override  
  2. public boolean superDispatchTouchEvent(MotionEvent event) {  
  3.     return mDecor.superDispatchTouchEvent(event);  
  4. }  
    @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);
    }

        从superDispatchTouchEvent()方法中可以看到,它又调用了mDecor的superDispatchTouchEvent()方法,再看mDecor的superDispatchTouchEvent()方法,

  1. public boolean superDispatchTouchEvent(MotionEvent event) {  
  2.     return super.dispatchTouchEvent(event);  
  3. }  
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }

       而mDecor是何许人也,其实就是PhoneWindow中的一个内部类DecorView的实例对象,是Activity的Window窗口中最根部的父容器,我们平时在Activity的onCreate()方法中,通过setContentView()给设置的布局容器,都属于mDecor的子View mContentView对象的子view,而DecorView又继承于FrameLayout,FrameLayout又继承于ViewGroup,由此可知,Activity是如何将事件分发到相应的View当中去的:

 Activity.dispatchTouchEvent(MotionEvent event) -> PhoneWindow.superDispatchTouchEvent(MotionEvent event) -> DecorView.superDispatchTouchEvent(MotionEvent event) ->  FrameLayout.dispatchTouchEvent(MotionEvent event) -> ViewGroup.dispatchTouchEvent(MotionEvent event) -> 再逐级分发到各个ViewGroup/View当中去

        另外从以上分析过程可以看出,有一点需注意,就是我们在继承ViewGroup或其子类复写dispatchTouchEvent时,在方法最后的返回值处,最好别直接写成return true或者return false,而应写成super.dispatchTouchEvent,否则无法对事件继续进行逐级分发,因为在ViewGroup类的dispatchTouchEvent(MotionEvent event)方法中,会对该布局容器内的所有子View进行遍历,然后再进行事件分发,详细分发过程稍后会给出。

2、onInterceptTouchEvent(MotionEvent event) — 拦截事件

        onInterceptTouchEvent(MotionEvent event) 方法只存在于ViewGroup当中,是用来对布局容器内子View的事件进行拦截的,如果父容器View对事件进行了拦截,即return true,则子View不会收到任何事件分发。

3、onTouchEvent(MotionEvent event) — 处理消费事件

        onTouchEvent(MotionEvent event)方法如果返回true,则表示该事件被当前View给消费掉了,它的父View的onTouchEvent()后续都不会得到调用,而是通过dispatchTouchEvent()逐级向上返回true到Activity;如果没人消费该事件,都返回false,则最终会交给Activity去进行处理。

在大致了解了dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent的作用之后,现在我们最需要理清的就是这三者之间的调用关系如何,为此我自己写了一个测试Demo,界面如下:


屏幕中有ViewGroupA、ViewGroupB、ViewC,依次进行嵌套

测试代码如下:

  1. <com.android.hanyee.widgets.ViewGroupA xmlns:android=“http://schemas.android.com/apk/res/android”  
  2.     android:id=“@+id/viewGroupA”  
  3.     android:layout_width=“match_parent”  
  4.     android:layout_height=“match_parent”  
  5.     android:orientation=“vertical”  
  6.     android:background=“@android:color/white”>  
  7.   
  8.     <com.android.hanyee.widgets.ViewGroupB  
  9.         android:id=“@+id/viewGroupB”  
  10.         android:layout_width=“match_parent”  
  11.         android:layout_height=“match_parent”  
  12.         android:layout_margin=“60dp”  
  13.         android:orientation=“vertical”  
  14.         android:background=“@android:color/holo_blue_dark”>  
  15.   
  16.         <com.android.hanyee.widgets.ViewC  
  17.             android:layout_width=“match_parent”  
  18.             android:layout_height=“match_parent”  
  19.             android:layout_margin=“60dp”  
  20.             android:background=“@android:color/holo_green_dark” />  
  21.     </com.android.hanyee.widgets.ViewGroupB>  
  22. </com.android.hanyee.widgets.ViewGroupA>  
<com.android.hanyee.widgets.ViewGroupA xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/viewGroupA"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@android:color/white">

    <com.android.hanyee.widgets.ViewGroupB
        android:id="@+id/viewGroupB"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="60dp"
        android:orientation="vertical"
        android:background="@android:color/holo_blue_dark">

        <com.android.hanyee.widgets.ViewC
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="60dp"
            android:background="@android:color/holo_green_dark" />
    </com.android.hanyee.widgets.ViewGroupB>
</com.android.hanyee.widgets.ViewGroupA>

  1. public class ViewGroupA extends LinearLayout {  
  2.     public ViewGroupA(Context context) {  
  3.         super(context);  
  4.     }  
  5.   
  6.     public ViewGroupA(Context context, AttributeSet attrs) {  
  7.         super(context, attrs);  
  8.     }  
  9.   
  10.     public ViewGroupA(Context context, AttributeSet attrs, int defStyleAttr) {  
  11.         super(context, attrs, defStyleAttr);  
  12.     }  
  13.   
  14.     @Override  
  15.     public boolean onInterceptTouchEvent(MotionEvent ev) {  
  16.         Log.d(”hanyee”this.getClass().getSimpleName() + “ onInterceptTouchEvent -> ” + ViewUtils.actionToString(ev.getAction()));  
  17.         boolean result = super.onInterceptTouchEvent(ev);  
  18.         Log.d(”hanyee”this.getClass().getSimpleName() + “ onInterceptTouchEvent return super.onInterceptTouchEvent(ev)=” + result);  
  19.         return result;  
  20.     }  
  21.   
  22.     @Override  
  23.     public boolean dispatchTouchEvent(MotionEvent ev) {  
  24.         Log.d(”hanyee”this.getClass().getSimpleName() + “ dispatchTouchEvent -> ” + ViewUtils.actionToString(ev.getAction()));  
  25.         boolean result = super.dispatchTouchEvent(ev);  
  26.         Log.d(”hanyee”this.getClass().getSimpleName() + “ dispatchTouchEvent return super.dispatchTouchEvent(ev)= ” + result);  
  27.         return result;  
  28.     }  
  29.   
  30.     @Override  
  31.     public boolean onTouchEvent(MotionEvent ev) {  
  32.         Log.d(”hanyee”this.getClass().getSimpleName() + “ onTouchEvent -> ” + ViewUtils.actionToString(ev.getAction()));  
  33.         boolean result = super.onTouchEvent(ev);  
  34.         Log.d(”hanyee”this.getClass().getSimpleName() + “ onTouchEvent return super.onTouchEvent(ev)=” + result);  
  35.         return result;  
  36.     }  
  37.   
  38. }  
  39.   
  40. public class ViewGroupB extends LinearLayout {  
  41.     public ViewGroupB(Context context) {  
  42.         super(context);  
  43.     }  
  44.   
  45.     public ViewGroupB(Context context, AttributeSet attrs) {  
  46.         super(context, attrs);  
  47.     }  
  48.   
  49.     public ViewGroupB(Context context, AttributeSet attrs, int defStyleAttr) {  
  50.         super(context, attrs, defStyleAttr);  
  51.     }  
  52.   
  53.     @Override  
  54.     public boolean onInterceptTouchEvent(MotionEvent ev) {  
  55.         Log.d(”hanyee”this.getClass().getSimpleName() + “ onInterceptTouchEvent -> ” + ViewUtils.actionToString(ev.getAction()));  
  56.         boolean result = super.onInterceptTouchEvent(ev);  
  57.         Log.d(”hanyee”this.getClass().getSimpleName() + “ onInterceptTouchEvent return super.onInterceptTouchEvent(ev)=” + result);  
  58.         return result;  
  59.     }  
  60.   
  61.     @Override  
  62.     public boolean dispatchTouchEvent(MotionEvent ev) {  
  63.         Log.d(”hanyee”this.getClass().getSimpleName() + “ dispatchTouchEvent -> ” + ViewUtils.actionToString(ev.getAction()));  
  64.         boolean result = super.dispatchTouchEvent(ev);  
  65.         Log.d(”hanyee”this.getClass().getSimpleName() + “ dispatchTouchEvent return super.dispatchTouchEvent(ev)= ” + result);  
  66.         return result;  
  67.     }  
  68.   
  69.     @Override  
  70.     public boolean onTouchEvent(MotionEvent ev) {  
  71.         Log.d(”hanyee”this.getClass().getSimpleName() + “ onTouchEvent -> ” + ViewUtils.actionToString(ev.getAction()));  
  72.         boolean result = super.onTouchEvent(ev);  
  73.         Log.d(”hanyee”this.getClass().getSimpleName() + “ onTouchEvent return super.onTouchEvent(ev)=” + result);  
  74.         return result;  
  75.     }  
  76. }  
  77.   
  78. public class ViewC extends View {  
  79.     public ViewC(Context context) {  
  80.         super(context);  
  81.     }  
  82.   
  83.     public ViewC(Context context, AttributeSet attrs) {  
  84.         super(context, attrs);  
  85.     }  
  86.   
  87.     public ViewC(Context context, AttributeSet attrs, int defStyleAttr) {  
  88.         super(context, attrs, defStyleAttr);  
  89.     }  
  90.   
  91.     @Override  
  92.     public boolean dispatchTouchEvent(MotionEvent ev) {  
  93.         Log.d(”hanyee”this.getClass().getSimpleName() + “ dispatchTouchEvent -> ” + ViewUtils.actionToString(ev.getAction()));  
  94.         boolean result = super.dispatchTouchEvent(ev);  
  95.         Log.d(”hanyee”this.getClass().getSimpleName() + “ dispatchTouchEvent return super.dispatchTouchEvent(ev)= ” + result);  
  96.         return result;  
  97.     }  
  98.   
  99.     @Override  
  100.     public boolean onTouchEvent(MotionEvent ev) {  
  101.         Log.d(”hanyee”this.getClass().getSimpleName() + “ onTouchEvent -> ” + ViewUtils.actionToString(ev.getAction()));  
  102.         boolean result = super.onTouchEvent(ev);  
  103.         Log.d(”hanyee”this.getClass().getSimpleName() + “ onTouchEvent return super.onTouchEvent(ev)=” + result);  
  104.         return result;  
  105.     }  
  106. }  
public class ViewGroupA extends LinearLayout {
    public ViewGroupA(Context context) {
        super(context);
    }

    public ViewGroupA(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ViewGroupA(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        Log.d("hanyee", this.getClass().getSimpleName() + " onInterceptTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
        boolean result = super.onInterceptTouchEvent(ev);
        Log.d("hanyee", this.getClass().getSimpleName() + " onInterceptTouchEvent return super.onInterceptTouchEvent(ev)=" + result);
        return result;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
        boolean result = super.dispatchTouchEvent(ev);
        Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent return super.dispatchTouchEvent(ev)= " + result);
        return result;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
        boolean result = super.onTouchEvent(ev);
        Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent return super.onTouchEvent(ev)=" + result);
        return result;
    }

}

public class ViewGroupB extends LinearLayout {
    public ViewGroupB(Context context) {
        super(context);
    }

    public ViewGroupB(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ViewGroupB(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        Log.d("hanyee", this.getClass().getSimpleName() + " onInterceptTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
        boolean result = super.onInterceptTouchEvent(ev);
        Log.d("hanyee", this.getClass().getSimpleName() + " onInterceptTouchEvent return super.onInterceptTouchEvent(ev)=" + result);
        return result;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
        boolean result = super.dispatchTouchEvent(ev);
        Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent return super.dispatchTouchEvent(ev)= " + result);
        return result;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
        boolean result = super.onTouchEvent(ev);
        Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent return super.onTouchEvent(ev)=" + result);
        return result;
    }
}

public class ViewC extends View {
    public ViewC(Context context) {
        super(context);
    }

    public ViewC(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ViewC(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
        boolean result = super.dispatchTouchEvent(ev);
        Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent return super.dispatchTouchEvent(ev)= " + result);
        return result;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
        boolean result = super.onTouchEvent(ev);
        Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent return super.onTouchEvent(ev)=" + result);
        return result;
    }
}

测试情景1:ViewGroupA、ViewGroupB、ViewC都没有消费事件

测试结果如下图:


由图中log可以看出,如果没有任何view消费事件的话,事件的传递顺序如下:

ViewGroupA.dispatchTouchEvent -> ViewGroupA.onInterceptTouchEvent(return false, 没有进行拦截) -> ViewGroupB.dispatchTouchEvent -> ViewGroupB.onInterceptTouchEvent(return false, 没有进行拦截) -> ViewC.dispatchTouchEvent -> ViewC.onTouchEvent(return false, 没有消费)  -> ViewC.dispatchTouchEvent(return false, 将onTouchEvent的处理结果回传给ViewGroupB) -> ViewGroupB.onTouchEvent(return false, 也没有消费)  -> ViewB.dispatchTouchEvent(return false, 将onTouchEvent的处理结果回传给ViewGroupA) -> ViewGroupA.onTouchEvent(return false, 也没有消费)  -> ViewA.dispatchTouchEvent(return false, 最终将onTouchEvent的处理结果回传给Activity) -> Activity对事件进行最终处理

看到这里大伙可能会有些疑问,怎么就只有Down事件,而没有后续的Move、Up等事件,这是因为没有任何子View消费Down事件,Down事件最终被最外层的Activity给处理掉了,所以后续的所有Move、Up等事件都不会再分发给子View了,这里在后面的源码分析时会提到。

测试情景2:ViewC消费了事件

测试结果如下图:


由图中的log可以看出,一旦ViewC消费了Down事件,它的父容器ViewGroupB,祖父容器ViewGroupA的onTouchEvent都不会被调用了,而是直接通过dispatchTouchEvent将Down以及后续的Move、Up事件的处理结果返回至Activity。

测试情景3:仅点击ViewGroupB,让ViewGroupB消费事件

测试结果如下图:


从图中log可以看出,如果点击ViewGroupB,事件根本就不会传递到ViewC,ViewGroupB在消费了Down事件之后,再直接由父容器ViewGroupA的dispatchTouchEvent将ViewGroupB的onTouchEvent处理结果true回传给Activity,接下来后续的Move、Up事件都只会传递至ViewGroupB,而不会分发给ViewC。

测试情景4:让ViewGroupB对事件进行拦截

测试结果如图:


从图中log可以看出,如果ViewGroupB的onInterceptTouchEvent 返回true,对子view的事件进行拦截,则ViewC不会收到任何的点击事件,事件流变成了ViewGroupA –>ViewGroupB –> ViewGroupA,而没有经过ViewC

通过上述几种情景,我们可以大致了解,ViewGroupA的dispatchTouchEvent最先被调用,主要负责事件分发,然后会调用其onInterceptTouchEvent,如果返回true,则后续的ViewGroupB、ViewC都不会收到任何的点击事件,相反如果返回false,就放弃拦截事件,接着会遍历调用子View的dispatchTouchEvent方法将事件分发给ViewGroupB,如果ViewGroupB也没有拦截事件,则又会遍历调用子View的dispatchTouchEvent方法将事件分发给ViewC,如果ViewC在onTouchEvent中消费了事件返回true,则会将true通过dispatchTouchEvent方法逐级返回给其父容器直至Activity中,而且不会调用各个父容器对应的onTouchEvent方法,如果子View在onTouchEvent中没消费事件返回false,则通过dispatchTouchEvent方法将false返回给ViewGroupB,ViewGroupB就知道子View没有消费事件,就会调用自己的onTouchEvent来处理该事件,然后同理递归着ViewC在onTouchEvent中对于事件的处理逻辑,直到ViewGroupA将事件处理完反馈给Activity。

前面列了这么多现象,并归纳总结出以上dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent之间的调用关系,相信大家对于Android事件的分发机制已经有了较为清晰的认识,但作为一名程序员,知其然,还得知其所以然,下面就带领大家一起研读下源码,看看到底为啥是这样的调用关系。从上面的情景log中大家应该可以看出,事件分发机制的最初始的入口就是ViewGroup的dispatchTouchEvent,下面就看看其代码:

  1. @Override  
  2. public boolean dispatchTouchEvent(MotionEvent ev) {  
  3.     if (mInputEventConsistencyVerifier != null) {  
  4.         mInputEventConsistencyVerifier.onTouchEvent(ev, 1);  
  5.     }  
  6.   
  7.     // If the event targets the accessibility focused view and this is it, start  
  8.     // normal event dispatch. Maybe a descendant is what will handle the click.  
  9.     if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {  
  10.         ev.setTargetAccessibilityFocus(false);  
  11.     }  
  12.   
  13.     boolean handled = false;  
  14.     if (onFilterTouchEventForSecurity(ev)) {  
  15.         final int action = ev.getAction();  
  16.         final int actionMasked = action & MotionEvent.ACTION_MASK;  
  17.   
  18.         // Handle an initial down.  
  19.         if (actionMasked == MotionEvent.ACTION_DOWN) {  
  20.             // Throw away all previous state when starting a new touch gesture.  
  21.             // The framework may have dropped the up or cancel event for the previous gesture  
  22.             // due to an app switch, ANR, or some other state change.  
  23.             cancelAndClearTouchTargets(ev);  
  24.             resetTouchState();  
  25.         }  
  26.   
  27.         // Check for interception.  
  28.         final boolean intercepted;  
  29.         if (actionMasked == MotionEvent.ACTION_DOWN  
  30.                 || mFirstTouchTarget != null) {  
  31.             final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;  
  32.             if (!disallowIntercept) {  
  33.                 intercepted = onInterceptTouchEvent(ev);  
  34.                 ev.setAction(action); // restore action in case it was changed  
  35.             } else {  
  36.                 intercepted = false;  
  37.             }  
  38.         } else {  
  39.             // There are no touch targets and this action is not an initial down  
  40.             // so this view group continues to intercept touches.  
  41.             intercepted = true;  
  42.         }  
  43.   
  44.         // If intercepted, start normal event dispatch. Also if there is already  
  45.         // a view that is handling the gesture, do normal event dispatch.  
  46.         if (intercepted || mFirstTouchTarget != null) {  
  47.             ev.setTargetAccessibilityFocus(false);  
  48.         }  
  49.   
  50.         // Check for cancelation.  
  51.         final boolean canceled = resetCancelNextUpFlag(this)  
  52.                 || actionMasked == MotionEvent.ACTION_CANCEL;  
  53.   
  54.         // Update list of touch targets for pointer down, if needed.  
  55.         final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;  
  56.         TouchTarget newTouchTarget = null;  
  57.         boolean alreadyDispatchedToNewTouchTarget = false;  
  58.         if (!canceled && !intercepted) {  
  59.   
  60.             // If the event is targeting accessiiblity focus we give it to the  
  61.             // view that has accessibility focus and if it does not handle it  
  62.             // we clear the flag and dispatch the event to all children as usual.  
  63.             // We are looking up the accessibility focused host to avoid keeping  
  64.             // state since these events are very rare.  
  65.             View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()  
  66.                     ? findChildWithAccessibilityFocus() : null;  
  67.   
  68.             if (actionMasked == MotionEvent.ACTION_DOWN  
  69.                     || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)  
  70.                     || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {  
  71.                 final int actionIndex = ev.getActionIndex(); // always 0 for down  
  72.                 final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)  
  73.                         : TouchTarget.ALL_POINTER_IDS;  
  74.   
  75.                 // Clean up earlier touch targets for this pointer id in case they  
  76.                 // have become out of sync.  
  77.                 removePointersFromTouchTargets(idBitsToAssign);  
  78.   
  79.                 final int childrenCount = mChildrenCount;  
  80.                 if (newTouchTarget == null && childrenCount != 0) {  
  81.                     final float x = ev.getX(actionIndex);  
  82.                     final float y = ev.getY(actionIndex);  
  83.                     // Find a child that can receive the event.  
  84.                     // Scan children from front to back.  
  85.                     final ArrayList<View> preorderedList = buildOrderedChildList();  
  86.                     final boolean customOrder = preorderedList == null  
  87.                             && isChildrenDrawingOrderEnabled();  
  88.                     final View[] children = mChildren;  
  89.                     for (int i = childrenCount - 1; i >= 0; i–) {  
  90.                         final int childIndex = customOrder  
  91.                                 ? getChildDrawingOrder(childrenCount, i) : i;  
  92.                         final View child = (preorderedList == null)  
  93.                                 ? children[childIndex] : preorderedList.get(childIndex);  
  94.   
  95.                         // If there is a view that has accessibility focus we want it  
  96.                         // to get the event first and if not handled we will perform a  
  97.                         // normal dispatch. We may do a double iteration but this is  
  98.                         // safer given the timeframe.  
  99.                         if (childWithAccessibilityFocus != null) {  
  100.                             if (childWithAccessibilityFocus != child) {  
  101.                                 continue;  
  102.                             }  
  103.                             childWithAccessibilityFocus = null;  
  104.                             i = childrenCount - 1;  
  105.                         }  
  106.   
  107.                         if (!canViewReceivePointerEvents(child)  
  108.                                 || !isTransformedTouchPointInView(x, y, child, null)) {  
  109.                             ev.setTargetAccessibilityFocus(false);  
  110.                             continue;  
  111.                         }  
  112.   
  113.                         newTouchTarget = getTouchTarget(child);  
  114.                         if (newTouchTarget != null) {  
  115.                             // Child is already receiving touch within its bounds.  
  116.                             // Give it the new pointer in addition to the ones it is handling.  
  117.                             newTouchTarget.pointerIdBits |= idBitsToAssign;  
  118.                             break;  
  119.                         }  
  120.   
  121.                         resetCancelNextUpFlag(child);  
  122.                         if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {  
  123.                             // Child wants to receive touch within its bounds.  
  124.                             mLastTouchDownTime = ev.getDownTime();  
  125.                             if (preorderedList != null) {  
  126.                                 // childIndex points into presorted list, find original index  
  127.                                 for (int j = 0; j < childrenCount; j++) {  
  128.                                     if (children[childIndex] == mChildren[j]) {  
  129.                                         mLastTouchDownIndex = j;  
  130.                                         break;  
  131.                                     }  
  132.                                 }  
  133.                             } else {  
  134.                                 mLastTouchDownIndex = childIndex;  
  135.                             }  
  136.                             mLastTouchDownX = ev.getX();  
  137.                             mLastTouchDownY = ev.getY();  
  138.                             newTouchTarget = addTouchTarget(child, idBitsToAssign);  
  139.                             alreadyDispatchedToNewTouchTarget = true;  
  140.                             break;  
  141.                         }  
  142.   
  143.                         // The accessibility focus didn’t handle the event, so clear  
  144.                         // the flag and do a normal dispatch to all children.  
  145.                         ev.setTargetAccessibilityFocus(false);  
  146.                     }  
  147.                     if (preorderedList != null) preorderedList.clear();  
  148.                 }  
  149.   
  150.                 if (newTouchTarget == null && mFirstTouchTarget != null) {  
  151.                     // Did not find a child to receive the event.  
  152.                     // Assign the pointer to the least recently added target.  
  153.                     newTouchTarget = mFirstTouchTarget;  
  154.                     while (newTouchTarget.next != null) {  
  155.                         newTouchTarget = newTouchTarget.next;  
  156.                     }  
  157.                     newTouchTarget.pointerIdBits |= idBitsToAssign;  
  158.                 }  
  159.             }  
  160.         }  
  161.   
  162.         // Dispatch to touch targets.  
  163.         if (mFirstTouchTarget == null) {  
  164.             // No touch targets so treat this as an ordinary view.  
  165.             handled = dispatchTransformedTouchEvent(ev, canceled, null,  
  166.                     TouchTarget.ALL_POINTER_IDS);  
  167.         } else {  
  168.             // Dispatch to touch targets, excluding the new touch target if we already  
  169.             // dispatched to it.  Cancel touch targets if necessary.  
  170.             TouchTarget predecessor = null;  
  171.             TouchTarget target = mFirstTouchTarget;  
  172.             while (target != null) {  
  173.                 final TouchTarget next = target.next;  
  174.                 if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {  
  175.                     handled = true;  
  176.                 } else {  
  177.                     final boolean cancelChild = resetCancelNextUpFlag(target.child)  
  178.                             || intercepted;  
  179.                     if (dispatchTransformedTouchEvent(ev, cancelChild,  
  180.                             target.child, target.pointerIdBits)) {  
  181.                         handled = true;  
  182.                     }  
  183.                     if (cancelChild) {  
  184.                         if (predecessor == null) {  
  185.                             mFirstTouchTarget = next;  
  186.                         } else {  
  187.                             predecessor.next = next;  
  188.                         }  
  189.                         target.recycle();  
  190.                         target = next;  
  191.                         continue;  
  192.                     }  
  193.                 }  
  194.                 predecessor = target;  
  195.                 target = next;  
  196.             }  
  197.         }  
  198.   
  199.         // Update list of touch targets for pointer up or cancel, if needed.  
  200.         if (canceled  
  201.                 || actionMasked == MotionEvent.ACTION_UP  
  202.                 || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {  
  203.             resetTouchState();  
  204.         } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {  
  205.             final int actionIndex = ev.getActionIndex();  
  206.             final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);  
  207.             removePointersFromTouchTargets(idBitsToRemove);  
  208.         }  
  209.     }  
  210.   
  211.     if (!handled && mInputEventConsistencyVerifier != null) {  
  212.         mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);  
  213.     }  
  214.     return handled;  
  215. }  
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }

        // If the event targets the accessibility focused view and this is it, start
        // normal event dispatch. Maybe a descendant is what will handle the click.
        if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
            ev.setTargetAccessibilityFocus(false);
        }

        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            // Handle an initial down.
            if (actionMasked == MotionEvent.ACTION_DOWN) {
                // Throw away all previous state when starting a new touch gesture.
                // The framework may have dropped the up or cancel event for the previous gesture
                // due to an app switch, ANR, or some other state change.
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }

            // Check for interception.
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    intercepted = false;
                }
            } else {
                // There are no touch targets and this action is not an initial down
                // so this view group continues to intercept touches.
                intercepted = true;
            }

            // If intercepted, start normal event dispatch. Also if there is already
            // a view that is handling the gesture, do normal event dispatch.
            if (intercepted || mFirstTouchTarget != null) {
                ev.setTargetAccessibilityFocus(false);
            }

            // Check for cancelation.
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

            // Update list of touch targets for pointer down, if needed.
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
            if (!canceled && !intercepted) {

                // If the event is targeting accessiiblity focus we give it to the
                // view that has accessibility focus and if it does not handle it
                // we clear the flag and dispatch the event to all children as usual.
                // We are looking up the accessibility focused host to avoid keeping
                // state since these events are very rare.
                View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
                        ? findChildWithAccessibilityFocus() : null;

                if (actionMasked == MotionEvent.ACTION_DOWN
                        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                    final int actionIndex = ev.getActionIndex(); // always 0 for down
                    final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
                            : TouchTarget.ALL_POINTER_IDS;

                    // Clean up earlier touch targets for this pointer id in case they
                    // have become out of sync.
                    removePointersFromTouchTargets(idBitsToAssign);

                    final int childrenCount = mChildrenCount;
                    if (newTouchTarget == null && childrenCount != 0) {
                        final float x = ev.getX(actionIndex);
                        final float y = ev.getY(actionIndex);
                        // Find a child that can receive the event.
                        // Scan children from front to back.
                        final ArrayList<View> preorderedList = buildOrderedChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = customOrder
                                    ? getChildDrawingOrder(childrenCount, i) : i;
                            final View child = (preorderedList == null)
                                    ? children[childIndex] : preorderedList.get(childIndex);

                            // If there is a view that has accessibility focus we want it
                            // to get the event first and if not handled we will perform a
                            // normal dispatch. We may do a double iteration but this is
                            // safer given the timeframe.
                            if (childWithAccessibilityFocus != null) {
                                if (childWithAccessibilityFocus != child) {
                                    continue;
                                }
                                childWithAccessibilityFocus = null;
                                i = childrenCount - 1;
                            }

                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }

                            newTouchTarget = getTouchTarget(child);
                            if (newTouchTarget != null) {
                                // Child is already receiving touch within its bounds.
                                // Give it the new pointer in addition to the ones it is handling.
                                newTouchTarget.pointerIdBits |= idBitsToAssign;
                                break;
                            }

                            resetCancelNextUpFlag(child);
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                // Child wants to receive touch within its bounds.
                                mLastTouchDownTime = ev.getDownTime();
                                if (preorderedList != null) {
                                    // childIndex points into presorted list, find original index
                                    for (int j = 0; j < childrenCount; j++) {
                                        if (children[childIndex] == mChildren[j]) {
                                            mLastTouchDownIndex = j;
                                            break;
                                        }
                                    }
                                } else {
                                    mLastTouchDownIndex = childIndex;
                                }
                                mLastTouchDownX = ev.getX();
                                mLastTouchDownY = ev.getY();
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }

                            // The accessibility focus didn't handle the event, so clear
                            // the flag and do a normal dispatch to all children.
                            ev.setTargetAccessibilityFocus(false);
                        }
                        if (preorderedList != null) preorderedList.clear();
                    }

                    if (newTouchTarget == null && mFirstTouchTarget != null) {
                        // Did not find a child to receive the event.
                        // Assign the pointer to the least recently added target.
                        newTouchTarget = mFirstTouchTarget;
                        while (newTouchTarget.next != null) {
                            newTouchTarget = newTouchTarget.next;
                        }
                        newTouchTarget.pointerIdBits |= idBitsToAssign;
                    }
                }
            }

            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
                // Dispatch to touch targets, excluding the new touch target if we already
                // dispatched to it.  Cancel touch targets if necessary.
                TouchTarget predecessor = null;
                TouchTarget target = mFirstTouchTarget;
                while (target != null) {
                    final TouchTarget next = target.next;
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            handled = true;
                        }
                        if (cancelChild) {
                            if (predecessor == null) {
                                mFirstTouchTarget = next;
                            } else {
                                predecessor.next = next;
                            }
                            target.recycle();
                            target = next;
                            continue;
                        }
                    }
                    predecessor = target;
                    target = next;
                }
            }

            // Update list of touch targets for pointer up or cancel, if needed.
            if (canceled
                    || actionMasked == MotionEvent.ACTION_UP
                    || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                resetTouchState();
            } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
                final int actionIndex = ev.getActionIndex();
                final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
                removePointersFromTouchTargets(idBitsToRemove);
            }
        }

        if (!handled && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
        }
        return handled;
    }

这方法看似比较长,但我们只挑比较重要的点来看,在第32行会根据disallowIntercept来判断是否对子view来进行事件拦截,子view可以通过调用requestDisallowInterceptTouchEvent()方法来改变其值,如果可以进行拦截,则会调用onInterceptTouchEvent()方法,根据其返回值来判断需不需要对子View进行拦截,默认情况下onInterceptTouchEvent()方法返回的是false,所以如果我们在自定义View时如果想拦截的话,可以重写这个方法返回true就行了。

然后在第58行的if条件中,会根据是否取消canceled以及之前的是否拦截的标志intercepted来判断是否走进下面的逻辑代码块,这里我们只看intercepted,如果没有拦截,则会进入if后面的逻辑代码块,直到第89行的for循环,我们会看到ViewGroup在对所有子View进行遍历,以方便接下来的事件分发,再看到107、108行的判断,canViewReceivePointerEvents()用来判断是否该View能够接受处理事件,

  1. private static boolean canViewReceivePointerEvents(View child) {  
  2.     return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE  
  3.             || child.getAnimation() != null;  
  4. }  
    private static boolean canViewReceivePointerEvents(View child) {
        return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE
                || child.getAnimation() != null;
    }
可以看到只有当view处于可见状态且没有做动画时才能接收处理事件,再看isTransformedTouchPointInView()是用来判断当前事件是否触发在该view的范围之内,这里我们可以回想前面的测试情景3,当我们点击ViewGroupB时,ViewC完全没有收到任何事件,就是因为点击事件不在ViewC的范围之类,在isTransformedTouchPointInView()进行判断时就给过滤掉了,所以ViewC不会收到任何分发的事件。再看看第122行,会调用dispatchTransformedTouchEvent()来将事件分发给对应的view进行处理,让我们进入其方法体看看,

  1. private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,  
  2.         View child, int desiredPointerIdBits) {  
  3.     final boolean handled;  
  4.   
  5.     // Canceling motions is a special case.  We don’t need to perform any transformations  
  6.     // or filtering.  The important part is the action, not the contents.  
  7.     final int oldAction = event.getAction();  
  8.     if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {  
  9.         event.setAction(MotionEvent.ACTION_CANCEL);  
  10.         if (child == null) {  
  11.             handled = super.dispatchTouchEvent(event);  
  12.         } else {  
  13.             handled = child.dispatchTouchEvent(event);  
  14.         }  
  15.         event.setAction(oldAction);  
  16.         return handled;  
  17.     }  
  18.   
  19.     // Calculate the number of pointers to deliver.  
  20.     final int oldPointerIdBits = event.getPointerIdBits();  
  21.     final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;  
  22.   
  23.     // If for some reason we ended up in an inconsistent state where it looks like we  
  24.     // might produce a motion event with no pointers in it, then drop the event.  
  25.     if (newPointerIdBits == 0) {  
  26.         return false;  
  27.     }  
  28.   
  29.     // If the number of pointers is the same and we don’t need to perform any fancy  
  30.     // irreversible transformations, then we can reuse the motion event for this  
  31.     // dispatch as long as we are careful to revert any changes we make.  
  32.     // Otherwise we need to make a copy.  
  33.     final MotionEvent transformedEvent;  
  34.     if (newPointerIdBits == oldPointerIdBits) {  
  35.         if (child == null || child.hasIdentityMatrix()) {  
  36.             if (child == null) {  
  37.                 handled = super.dispatchTouchEvent(event);  
  38.             } else {  
  39.                 final float offsetX = mScrollX - child.mLeft;  
  40.                 final float offsetY = mScrollY - child.mTop;  
  41.                 event.offsetLocation(offsetX, offsetY);  
  42.   
  43.                 handled = child.dispatchTouchEvent(event);  
  44.   
  45.                 event.offsetLocation(-offsetX, -offsetY);  
  46.             }  
  47.             return handled;  
  48.         }  
  49.         transformedEvent = MotionEvent.obtain(event);  
  50.     } else {  
  51.         transformedEvent = event.split(newPointerIdBits);  
  52.     }  
  53.   
  54.     // Perform any necessary transformations and dispatch.  
  55.     if (child == null) {  
  56.         handled = super.dispatchTouchEvent(transformedEvent);  
  57.     } else {  
  58.         final float offsetX = mScrollX - child.mLeft;  
  59.         final float offsetY = mScrollY - child.mTop;  
  60.         transformedEvent.offsetLocation(offsetX, offsetY);  
  61.         if (! child.hasIdentityMatrix()) {  
  62.             transformedEvent.transform(child.getInverseMatrix());  
  63.         }  
  64.   
  65.         handled = child.dispatchTouchEvent(transformedEvent);  
  66.     }  
  67.   
  68.     // Done.  
  69.     transformedEvent.recycle();  
  70.     return handled;  
  71. }  
    private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        final boolean handled;

        // Canceling motions is a special case.  We don't need to perform any transformations
        // or filtering.  The important part is the action, not the contents.
        final int oldAction = event.getAction();
        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
            event.setAction(MotionEvent.ACTION_CANCEL);
            if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else {
                handled = child.dispatchTouchEvent(event);
            }
            event.setAction(oldAction);
            return handled;
        }

        // Calculate the number of pointers to deliver.
        final int oldPointerIdBits = event.getPointerIdBits();
        final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;

        // If for some reason we ended up in an inconsistent state where it looks like we
        // might produce a motion event with no pointers in it, then drop the event.
        if (newPointerIdBits == 0) {
            return false;
        }

        // If the number of pointers is the same and we don't need to perform any fancy
        // irreversible transformations, then we can reuse the motion event for this
        // dispatch as long as we are careful to revert any changes we make.
        // Otherwise we need to make a copy.
        final MotionEvent transformedEvent;
        if (newPointerIdBits == oldPointerIdBits) {
            if (child == null || child.hasIdentityMatrix()) {
                if (child == null) {
                    handled = super.dispatchTouchEvent(event);
                } else {
                    final float offsetX = mScrollX - child.mLeft;
                    final float offsetY = mScrollY - child.mTop;
                    event.offsetLocation(offsetX, offsetY);

                    handled = child.dispatchTouchEvent(event);

                    event.offsetLocation(-offsetX, -offsetY);
                }
                return handled;
            }
            transformedEvent = MotionEvent.obtain(event);
        } else {
            transformedEvent = event.split(newPointerIdBits);
        }

        // Perform any necessary transformations and dispatch.
        if (child == null) {
            handled = super.dispatchTouchEvent(transformedEvent);
        } else {
            final float offsetX = mScrollX - child.mLeft;
            final float offsetY = mScrollY - child.mTop;
            transformedEvent.offsetLocation(offsetX, offsetY);
            if (! child.hasIdentityMatrix()) {
                transformedEvent.transform(child.getInverseMatrix());
            }

            handled = child.dispatchTouchEvent(transformedEvent);
        }

        // Done.
        transformedEvent.recycle();
        return handled;
    }

我们看到在方法的末尾第55行,如果child为Null,则会调用ViewGroup的父类View的dispatchTouchEvent,否则就会调用child自身的dispatchTouchEvent方法进行事件分发处理。如果child是ViewGroup,则会又递归调用ViewGroup的dispatchTouchEvent方法逻辑进行事件分发,如果是View,则跟child为Null情况一样,都是会调到View的dispatchTouchEvent方法,接下来我们看看View的dispatchTouchEvent方法,

  1. public boolean dispatchTouchEvent(MotionEvent event) {  
  2.     // If the event should be handled by accessibility focus first.  
  3.     if (event.isTargetAccessibilityFocus()) {  
  4.         // We don’t have focus or no virtual descendant has it, do not handle the event.  
  5.         if (!isAccessibilityFocusedViewOrHost()) {  
  6.             return false;  
  7.         }  
  8.         // We have focus and got the event, then use normal event dispatch.  
  9.         event.setTargetAccessibilityFocus(false);  
  10.     }  
  11.   
  12.     boolean result = false;  
  13.   
  14.     if (mInputEventConsistencyVerifier != null) {  
  15.         mInputEventConsistencyVerifier.onTouchEvent(event, 0);  
  16.     }  
  17.   
  18.     final int actionMasked = event.getActionMasked();  
  19.     if (actionMasked == MotionEvent.ACTION_DOWN) {  
  20.         // Defensive cleanup for new gesture  
  21.         stopNestedScroll();  
  22.     }  
  23.   
  24.     if (onFilterTouchEventForSecurity(event)) {  
  25.         //noinspection SimplifiableIfStatement  
  26.         ListenerInfo li = mListenerInfo;  
  27.         if (li != null && li.mOnTouchListener != null  
  28.                 && (mViewFlags & ENABLED_MASK) == ENABLED  
  29.                 && li.mOnTouchListener.onTouch(this, event)) {  
  30.             result = true;  
  31.         }  
  32.   
  33.         if (!result && onTouchEvent(event)) {  
  34.             result = true;  
  35.         }  
  36.     }  
  37.   
  38.     if (!result && mInputEventConsistencyVerifier != null) {  
  39.         mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);  
  40.     }  
  41.   
  42.     // Clean up after nested scrolls if this is the end of a gesture;  
  43.     // also cancel it if we tried an ACTION_DOWN but we didn’t want the rest  
  44.     // of the gesture.  
  45.     if (actionMasked == MotionEvent.ACTION_UP ||  
  46.             actionMasked == MotionEvent.ACTION_CANCEL ||  
  47.             (actionMasked == MotionEvent.ACTION_DOWN && !result)) {  
  48.         stopNestedScroll();  
  49.     }  
  50.   
  51.     return result;  
  52. }  
    public boolean dispatchTouchEvent(MotionEvent event) {
        // If the event should be handled by accessibility focus first.
        if (event.isTargetAccessibilityFocus()) {
            // We don't have focus or no virtual descendant has it, do not handle the event.
            if (!isAccessibilityFocusedViewOrHost()) {
                return false;
            }
            // We have focus and got the event, then use normal event dispatch.
            event.setTargetAccessibilityFocus(false);
        }

        boolean result = false;

        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }

        final int actionMasked = event.getActionMasked();
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // Defensive cleanup for new gesture
            stopNestedScroll();
        }

        if (onFilterTouchEventForSecurity(event)) {
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }

            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }

        if (!result && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }

        // Clean up after nested scrolls if this is the end of a gesture;
        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
        // of the gesture.
        if (actionMasked == MotionEvent.ACTION_UP ||
                actionMasked == MotionEvent.ACTION_CANCEL ||
                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
            stopNestedScroll();
        }

        return result;
    }
同样我们捡重点的看,第23行用来做过滤,看是否有窗口覆盖在上面,第27~29行三个判断条件说明了,当View的touch事件监听器不为空,View是enable状态,且touch事件监听回调方法onTouch方法返回true三个条件同时满足时,则会最终返回true,而且第33行的onTouchEvent方法都不会得到执行,这说明View的OnTouchListener监听回调的优先级要高于onTouchEvent,如果我们给View设置了OnTouchListener监听,并且在回调方法onTouch()中返回true,View的onTouchEvent就得不到执行,其dispatchTouchEvent方法就会直接返回true给父容器,相反如果返回false,或者没有设置OnTouchListener监听,才会执行onTouchEvent()方法对分发来的事件进行处理。接着再去看看onTouchEvent()中如何对事件进行处理的,

  1. public boolean onTouchEvent(MotionEvent event) {  
  2.     final float x = event.getX();  
  3.     final float y = event.getY();  
  4.     final int viewFlags = mViewFlags;  
  5.     final int action = event.getAction();  
  6.   
  7.     if ((viewFlags & ENABLED_MASK) == DISABLED) {  
  8.         if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {  
  9.             setPressed(false);  
  10.         }  
  11.         // A disabled view that is clickable still consumes the touch  
  12.         // events, it just doesn’t respond to them.  
  13.         return (((viewFlags & CLICKABLE) == CLICKABLE  
  14.                 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)  
  15.                 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);  
  16.     }  
  17.   
  18.     if (mTouchDelegate != null) {  
  19.         if (mTouchDelegate.onTouchEvent(event)) {  
  20.             return true;  
  21.         }  
  22.     }  
  23.   
  24.     if (((viewFlags & CLICKABLE) == CLICKABLE ||  
  25.             (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||  
  26.             (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {  
  27.         switch (action) {  
  28.             case MotionEvent.ACTION_UP:  
  29.                 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;  
  30.                 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {  
  31.                     // take focus if we don’t have it already and we should in  
  32.                     // touch mode.  
  33.                     boolean focusTaken = false;  
  34.                     if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {  
  35.                         focusTaken = requestFocus();  
  36.                     }  
  37.   
  38.                     if (prepressed) {  
  39.                         // The button is being released before we actually  
  40.                         // showed it as pressed.  Make it show the pressed  
  41.                         // state now (before scheduling the click) to ensure  
  42.                         // the user sees it.  
  43.                         setPressed(true, x, y);  
  44.                    }  
  45.   
  46.                     if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {  
  47.                         // This is a tap, so remove the longpress check  
  48.                         removeLongPressCallback();  
  49.   
  50.                         // Only perform take click actions if we were in the pressed state  
  51.                         if (!focusTaken) {  
  52.                             // Use a Runnable and post this rather than calling  
  53.                             // performClick directly. This lets other visual state  
  54.                             // of the view update before click actions start.  
  55.                             if (mPerformClick == null) {  
  56.                                 mPerformClick = new PerformClick();  
  57.                             }  
  58.                             if (!post(mPerformClick)) {  
  59.                                 performClick();  
  60.                             }  
  61.                         }  
  62.                     }  
  63.   
  64.                     if (mUnsetPressedState == null) {  
  65.                         mUnsetPressedState = new UnsetPressedState();  
  66.                     }  
  67.   
  68.                     if (prepressed) {  
  69.                         postDelayed(mUnsetPressedState,  
  70.                                 ViewConfiguration.getPressedStateDuration());  
  71.                     } else if (!post(mUnsetPressedState)) {  
  72.                         // If the post failed, unpress right now  
  73.                         mUnsetPressedState.run();  
  74.                     }  
  75.   
  76.                     removeTapCallback();  
  77.                 }  
  78.                 mIgnoreNextUpEvent = false;  
  79.                 break;  
  80.   
  81.             case MotionEvent.ACTION_DOWN:  
  82.                 mHasPerformedLongPress = false;  
  83.   
  84.                 if (performButtonActionOnTouchDown(event)) {  
  85.                     break;  
  86.                 }  
  87.   
  88.                 // Walk up the hierarchy to determine if we’re inside a scrolling container.  
  89.                 boolean isInScrollingContainer = isInScrollingContainer();  
  90.   
  91.                 // For views inside a scrolling container, delay the pressed feedback for  
  92.                 // a short period in case this is a scroll.  
  93.                 if (isInScrollingContainer) {  
  94.                     mPrivateFlags |= PFLAG_PREPRESSED;  
  95.                     if (mPendingCheckForTap == null) {  
  96.                         mPendingCheckForTap = new CheckForTap();  
  97.                     }  
  98.                     mPendingCheckForTap.x = event.getX();  
  99.                     mPendingCheckForTap.y = event.getY();  
  100.                     postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());  
  101.                 } else {  
  102.                     // Not inside a scrolling container, so show the feedback right away  
  103.                     setPressed(true, x, y);  
  104.                     checkForLongClick(0);  
  105.                 }  
  106.                 break;  
  107.   
  108.             case MotionEvent.ACTION_CANCEL:  
  109.                 setPressed(false);  
  110.                 removeTapCallback();  
  111.                 removeLongPressCallback();  
  112.                 mInContextButtonPress = false;  
  113.                 mHasPerformedLongPress = false;  
  114.                 mIgnoreNextUpEvent = false;  
  115.                 break;  
  116.   
  117.             case MotionEvent.ACTION_MOVE:  
  118.                 drawableHotspotChanged(x, y);  
  119.   
  120.                 // Be lenient about moving outside of buttons  
  121.                 if (!pointInView(x, y, mTouchSlop)) {  
  122.                     // Outside button  
  123.                     removeTapCallback();  
  124.                     if ((mPrivateFlags & PFLAG_PRESSED) != 0) {  
  125.                         // Remove any future long press/tap checks  
  126.                         removeLongPressCallback();  
  127.   
  128.                         setPressed(false);  
  129.                     }  
  130.                 }  
  131.                 break;  
  132.         }  
  133.   
  134.         return true;  
  135.     }  
  136.   
  137.     return false;  
  138. }  
    public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                setPressed(false);
            }
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
            return (((viewFlags & CLICKABLE) == CLICKABLE
                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
        }

        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }

        if (((viewFlags & CLICKABLE) == CLICKABLE ||
                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
            switch (action) {
                case MotionEvent.ACTION_UP:
                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
                        // take focus if we don't have it already and we should in
                        // touch mode.
                        boolean focusTaken = false;
                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                            focusTaken = requestFocus();
                        }

                        if (prepressed) {
                            // The button is being released before we actually
                            // showed it as pressed.  Make it show the pressed
                            // state now (before scheduling the click) to ensure
                            // the user sees it.
                            setPressed(true, x, y);
                       }

                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                            // This is a tap, so remove the longpress check
                            removeLongPressCallback();

                            // Only perform take click actions if we were in the pressed state
                            if (!focusTaken) {
                                // Use a Runnable and post this rather than calling
                                // performClick directly. This lets other visual state
                                // of the view update before click actions start.
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                if (!post(mPerformClick)) {
                                    performClick();
                                }
                            }
                        }

                        if (mUnsetPressedState == null) {
                            mUnsetPressedState = new UnsetPressedState();
                        }

                        if (prepressed) {
                            postDelayed(mUnsetPressedState,
                                    ViewConfiguration.getPressedStateDuration());
                        } else if (!post(mUnsetPressedState)) {
                            // If the post failed, unpress right now
                            mUnsetPressedState.run();
                        }

                        removeTapCallback();
                    }
                    mIgnoreNextUpEvent = false;
                    break;

                case MotionEvent.ACTION_DOWN:
                    mHasPerformedLongPress = false;

                    if (performButtonActionOnTouchDown(event)) {
                        break;
                    }

                    // Walk up the hierarchy to determine if we're inside a scrolling container.
                    boolean isInScrollingContainer = isInScrollingContainer();

                    // For views inside a scrolling container, delay the pressed feedback for
                    // a short period in case this is a scroll.
                    if (isInScrollingContainer) {
                        mPrivateFlags |= PFLAG_PREPRESSED;
                        if (mPendingCheckForTap == null) {
                            mPendingCheckForTap = new CheckForTap();
                        }
                        mPendingCheckForTap.x = event.getX();
                        mPendingCheckForTap.y = event.getY();
                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
                    } else {
                        // Not inside a scrolling container, so show the feedback right away
                        setPressed(true, x, y);
                        checkForLongClick(0);
                    }
                    break;

                case MotionEvent.ACTION_CANCEL:
                    setPressed(false);
                    removeTapCallback();
                    removeLongPressCallback();
                    mInContextButtonPress = false;
                    mHasPerformedLongPress = false;
                    mIgnoreNextUpEvent = false;
                    break;

                case MotionEvent.ACTION_MOVE:
                    drawableHotspotChanged(x, y);

                    // Be lenient about moving outside of buttons
                    if (!pointInView(x, y, mTouchSlop)) {
                        // Outside button
                        removeTapCallback();
                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                            // Remove any future long press/tap checks
                            removeLongPressCallback();

                            setPressed(false);
                        }
                    }
                    break;
            }

            return true;
        }

        return false;
    }

从第7~16行可以看出,当View为disable状态,而又clickable时,是会消费掉事件的,只不过在界面上没有任何的响应。第18~22行,关于TouchDelegate,根据对官方文档的理解就是说有两个View, ViewB在ViewA中,ViewA比较大,如果我们想点击ViewA的时候,让ViewB去响应点击事件,这时候就需要使用到TouchDelegate, 简单的理解就是如果该View有自己的事件委托处理人,就交给委托人处理。从第24~26行可以看出,只有当View是可点击状态时,才会进入对应各种事件的详细处理逻辑,否则会直接返回false,表明该事件没有被消费。在第59行,可以看到在Action_Up事件被触发时,会执行performClick(),也就是View的点击事件,由此可知,view的onClick()回调是在Action_Up事件中被触发的。第134行直接返回了true,可以看出只要View处于可点击状态,并且进入了switch的判断逻辑,就会被返回true,表明该事件被消费掉了,也就是说只要View是可点击的,事件传到了其OnTouchEvent,都会被消费掉。而平时我们在调用setOnClickListener方法给View设置点击事件监听时,都会将其点击状态修改为可点击状态。

  1. public void setOnClickListener(@Nullable OnClickListener l) {  
  2.     if (!isClickable()) {  
  3.         setClickable(true);  
  4.     }  
  5.     getListenerInfo().mOnClickListener = l;  
  6. }  
    public void setOnClickListener(@Nullable OnClickListener l) {
        if (!isClickable()) {
            setClickable(true);
        }
        getListenerInfo().mOnClickListener = l;
    }

追溯完View的事件分发流程,我们再返回到ViewGroup的dispatchTouchEvent方法的122行,如果对应得child消费了点击事件,就会通过对应的dispatchTouchEvent方法返回true并最终在122行使得条件成立,然后会进入到138行,调用addTouchTarget对newTouchTarget进行赋值,并且mFirstTouchTarget跟newTouchTarget的值都一样,然后将alreadyDispatchedToNewTouchTarget置为true

  1. private TouchTarget addTouchTarget(View child, int pointerIdBits) {  
  2.     TouchTarget target = TouchTarget.obtain(child, pointerIdBits);  
  3.     target.next = mFirstTouchTarget;  
  4.     mFirstTouchTarget = target;  
  5.     return target;  
  6. }  
    private TouchTarget addTouchTarget(View child, int pointerIdBits) {
        TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
        target.next = mFirstTouchTarget;
        mFirstTouchTarget = target;
        return target;
    }

然后来到了163行,由于mFirstTouchTarget和newTouchTarget在addTouchTarget中都被赋值了,所以会直接进入172行的while循环,由于之前在138、139行对mFirstTouchTarget、newTouchTarget、alreadyDispatchedToNewTouchTarget都赋值了,使得174行条件成立,所以就直接返回true了,至此,ViewGroup就完成了对子View的遍历及事件分发,由于事件被消费掉了,所以ViewGroup对应的所有外围容器都会递归回调dispatchTouchEvent将true传递给Activity,到这也就解释了测试情景2的产生原理。在Down相关事件被消费掉之后,后续的Move、Up事件在dispatchTouchEvent方法的68~70行不符合判断条件,直接会来到179行的dispatchTransformedTouchEvent方法继续进行分发,待子View进行消费。

如果在ViewGroup的dispatchTouchEvent方法第58行被拦截了(对应测试情景4),或者107~108行不成立(对应测试情景3),或者122行返回false(即子View没有消费事件,对应测试情景1),则会直接进入到第163行,这时mFirstTouchTarget肯定为空,所以会又调用dispatchTransformedTouchEvent方法,而且传进去的child为空,最终就会直接走到dispatchTransformedTouchEvent方法的55行,然后调用super.dispatchTouchEvent,之后的处理逻辑跟前面调View的dispatchTouchEvent逻辑一样。

终上所述,整个Android的事件分发机制可以大致概括成如下的流程图


PS:以上相关的系统代码均为Android6.0的系统源码,整个Android事件分发机制还算有点复杂,完全给整明白写下这篇文章还费了些时间,中间查阅了一些资料,可能有些地方还存在些理解偏差,还请大家指出相互学习进步







0
0
查看评论

Android6.0 ViewGroup/View 事件分发机制详解

以Android6.0的源码为基础,分析一下Android系统的ViewGroup/View Touch事件的分发机制
  • meiliwanghan
  • meiliwanghan
  • 2016-06-03 16:40
  • 4517

android之View和ViewGroup事件分发机制分析(一)(View的事件分发机制)

要把安卓学好,自定义View,事件分发机制,自定义动画之类的是必须掌握的,如果不想弄得那么高级来自定义,也可以不学。当初自己也是看了很多相关的书籍和博客文章,理了很久的思路。现在事件分发机制的分析已经理清楚了,而且记在笔记本上也不好,所以就提到博客上来了,对于事件分发机制,什么是事件分发机制呢?这个...
  • gsw333
  • gsw333
  • 2016-07-25 19:10
  • 626

Android View 事件分发机制源码详解(ViewGroup篇)

前言我们在学习View的时候,不可避免会遇到事件的分发,而往往遇到的很多滑动冲突的问题都是由于处理事件分发时不恰当所造成的。因此,深入了解View事件分发机制的原理,对于我们来说是很有必要的。由于View事件分发机制是一个比较复杂的机制,因此笔者将写成两篇文章来详细讲述,分别是ViewGroup和V...
  • a553181867
  • a553181867
  • 2016-04-30 21:05
  • 8631

android事件分发机制解析(配流程图)

事件分发机制 一.点击事件传播路径 1.点击事件TouchEvent最先是到达Activity的,然后传给Activity对应的window,再传给DecorView,再传给id为content的ViewGroup,即我们通过setContentView设置的ViewGroup,以此到最后的vi...
  • sggdjfkf147896325
  • sggdjfkf147896325
  • 2016-07-20 11:29
  • 520

Android View 事件分发机制 源码解析(ViewGroup篇)

本期三篇文章目录(可点击跳转)一. Android TouchEvent事件传递机制初识 二. android点击事件传递源码讲解(ViewGroup) 三.android点击事件传递源码讲解(View) 1. 前言android点击 事件一直以来都是很多安卓程序员的心病,之前通过demo模拟...
  • dfskhgalshgkajghljgh
  • dfskhgalshgkajghljgh
  • 2016-12-06 20:11
  • 1123

Andriod 从源码的角度详解View,ViewGroup的Touch事件的分发机制

今天这篇文章主要分析的是Android的事件分发机制,采用例子加源码的方式让大家深刻的理解Android事件分发的具体情况,虽然网上很多Android的事件分发的文章,有些还写的不错,但是我还是决定写这篇文章,用我自己的思维方式来帮助大家理解Android事件分发,Android事件分发到底有多重要...
  • xiaanming
  • xiaanming
  • 2014-03-24 09:20
  • 53602

Android中ViewGroup、View事件分发机制源码分析总结(雷惊风)

1.概述         很长时间没有回想Android中的事件分发机制了,打开目前的源码发现与两三年前的实现代码已经不一样了,5.0以后发生了变化,更加复杂了,但是万变不离其宗,实现原理还是一样的,在这里将5.0以前的时间分发机制做一下源码剖析及总结。会涉及...
  • liuyonglei1314
  • liuyonglei1314
  • 2017-04-01 11:24
  • 315

Android ViewGroup事件分发机制

上一篇已经完整的解析了Android View的事件分发机制,今天给大家代码ViewGroup事件分发的源码解析~~凡是自定义ViewGroup实现各种滑动效果的,不可避免的会出现很多事件的冲突,对ViewGroup事件分发机制的了解,也有益于大家了解冲突产生的原因,以及对冲突进行处理~1、案例首先...
  • lmj623565791
  • lmj623565791
  • 2014-09-09 09:38
  • 78145

Android 事件分发机制(最新源码6.0分析)--ViewGrop

ViewGroup的事件分发机制 上一张说到View的事件处理机制。而在Activity的dispatchTouchEvent()中最终定位到了ViewGroup()的事件分发: 上一章 请看:这里 Android  事件分发机制--View
  • u014800493
  • u014800493
  • 2016-07-28 16:07
  • 1911

Android View 事件分发机制 源码解析 (上)

一直想写事件分发机制的文章,不管咋样,也得自己研究下事件分发的源码,写出心得~首先我们先写个简单的例子来测试View的事件转发的流程~1、案例为了更好的研究View的事件转发,我们自定以一个MyButton继承Button,然后把跟事件传播有关的方法进行复写,然后添加上日志~MyButtonpack...
  • lmj623565791
  • lmj623565791
  • 2014-09-02 09:32
  • 62672
    个人资料
    • 访问:491593次
    • 积分:6793
    • 等级:
    • 排名:第4126名
    • 原创:274篇
    • 转载:63篇
    • 译文:0篇
    • 评论:51条