View事件分发机制源码分析

前沿

我们在前面学习了:
View的Measure过程源码分析
View的Layout过程源码分析
View的Draw过程源码分析
接下来我们学习View的事件传递机制。View的Measure,Layout,Draw和事件传递机制是自定义View必须要学习的。

事件的基础知识

1.什么是事件?
点击事件(Touch事件)
2.事件如何产生?
当用户触摸屏幕时(View 或 ViewGroup派生的控件),将产生点击事件(Touch事件)
注: Touch事件的相关细节(发生触摸的位置、时间等)被封装成MotionEvent对象
3.事件的分类
View的DOWN事件分发机制源码分析-LMLPHP
注: 从手指接触屏幕 至 手指离开屏幕,这个过程产生的一系列事件。一般情况下,事件列都是以DOWN事件开始、UP事件结束,中间有无数的MOVE事件(也可能没有MOVE事件)。
4.事件在哪些对象之间进行传递?
Activity、ViewGroup、View。
5.事件分发过程由哪些方法协作完成?
dispatchTouchEvent() 、onInterceptTouchEvent()和onTouchEvent()。
Activity和View没有onInterceptTouchEvent()方法。

MotionEvent.ACTION_DOWN事件的分发机制

我们先来看一张图:
View的DOWN事件分发机制源码分析-LMLPHP
你可能在什么地方见过?我是从图解 Android 事件分发机制中复制过来的。上面这张图说明了ACTION_DOWN事件在Activity、ViewGroup、View的dispatchTouchEvent() 、onInterceptTouchEvent()和onTouchEvent()方法中返回值不同有不同的走向。但上面这张图怎么来的呢?有这样图,对我们记住事件的分发过程确实有不少的帮助,尝试记住,但不过多久还是会忘。我们虽然从上面的图能清晰的看到DOWN事件的走向,但不知到这图怎么来的,即不知所以然。现在我们从源码的角度的来学习,分析上面那张的走向是怎么来的。
注:

  1. 上图说的是ACTION_DOWN事件,对MOVE和UP事件不适用。
  2. 上图的dispatchTouchEvent() 、onInterceptTouchEvent()和onTouchEvent()方法是我们继承Activity、ViewGroup、View分别重写的方法。

测试用的自定义类
先看一下我测试用的部分代码:
1.Activity用的布局

<?xml version="1.0" encoding="utf-8"?>
<com.xy.eventest.base.view.RootGroupView xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="#ffffff"
    android:gravity="center"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.xy.eventest.base.view.SubView
        android:id="@+id/subview_one"
        android:background="#ff0000"
        android:layout_height="100dp"
        android:layout_width="100dp"/>
</com.xy.eventest.base.view.RootGroupView>

RootGroupView 是继承ViewGroup的自定义View,重写了dispatchTouchEvent() 、onInterceptTouchEvent()和onTouchEvent()方法,后面会说到。
SubView 是继承View的自定义View。重写了dispatchTouchEvent() 、onTouchEvent()方法。

DOWN事件传到Activity层

我们先来看DOWN事件传到Activity层。我们重写Activity的dispatchTouchEvent()和onTouchEvent()方法。

 @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if( event.getAction() == MotionEvent.ACTION_DOWN ){
            Log.d(TAG , "dispatchTouch actoin = ACTION_DOWN " );
            return true ;// 或 flase
        }else if( event.getAction() == MotionEvent.ACTION_MOVE ){
            Log.d(TAG , "dispatchTouch actoin = ACTION_MOVE " );
            return super.dispatchTouchEvent(event);
        }else if( event.getAction() == MotionEvent.ACTION_UP ){
            Log.d(TAG , "dispatchTouch actoin = ACTION_UP " );
            return super.dispatchTouchEvent(event);
        }else if(event.getAction() == MotionEvent.ACTION_CANCEL){
            Log.d(TAG , "dispatchTouch actoin = ACTION_CANCEL " );
            return super.dispatchTouchEvent(event);
        }
        return  super.dispatchTouchEvent(event);;
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if( event.getAction() == MotionEvent.ACTION_DOWN ){
            Log.d(TAG , "onTouchEvent actoin = ACTION_DOWN " );
            return super.onTouchEvent(event);
        }else if( event.getAction() == MotionEvent.ACTION_MOVE ){
            Log.d(TAG , "onTouchEvent actoin = ACTION_MOVE " );
            return super.onTouchEvent(event);
        }else if( event.getAction() == MotionEvent.ACTION_UP ){
            Log.d(TAG , "onTouchEvent actoin = ACTION_UP " );
            return super.onTouchEvent(event);
        }else if(event.getAction() == MotionEvent.ACTION_CANCEL){
            Log.d(TAG , "onTouchEvent actoin = ACTION_CANCEL " );
            return super.onTouchEvent(event);
        }
        return super.onTouchEvent(event);
    }

1.重写Activity的dispatchTouchEvent()方法返回true或flase时,事件消费

我们从上图中看到,当我们重写Activity的dispatchTouchEvent()方法返回true或flase时,DOWN事件就不会在往下传递的了,在此处被消费了。为什么?我们知道DOWN是事件列的开始事件。当DOWN事件我们返回true或flase(没有调用Activity、ViewGroup和View的什么方法,所以DOWN事件就不会往下传递),即在此处被消费掉。

2.重写Activity的dispatchTouchEvent()方法返回默认(调用父类的方法super.dispatchTouchEvent(event))事件传递到ViewGroup(自定View)
我们从上图中看到,当我们重写Activity的dispatchTouchEvent()方法返回的是调用super.dispatchTouchEvent(event)方法的值时,DOWN事件会传到Activity使用的布局文件中最外存的View的dispatchTouchEvent()方法,最外层多数为继承ViewGroup的类(测试代码中的RootGroupView)。为什么?看源码:

调super.dispatchTouchEvent(event)方法,会走到Activity的dispatchTouchEvent()方法。

/**
  * 源码分析:Activity的dispatchTouchEvent()
  */
    public boolean dispatchTouchEvent(MotionEvent ev) {
            //  按下事件  = (一般事件列开始都是DOWN事件 ),故此处基本是true
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                onUserInteraction();// 分析【1】
            }
            // 若getWindow().superDispatchTouchEvent(ev)的返回true
            // 则Activity.dispatchTouchEvent()就返回true,则方法结束。即 :该点击事件停止往下传递 & 事件传递过程结束
            // 否则:继续往下调用Activity.onTouchEvent
            if (getWindow().superDispatchTouchEvent(ev)) { // 分析【2】
                return true;
            }
            return onTouchEvent(ev); // 继承了Activity,如果重写了onTouchEvent方法,那这里调用的是我们重写的onTouchEvent方法。
        }

/**
  * 分析【1】:onUserInteraction()
  * 作用:实现屏保功能
  * 注: a. 该方法为空方法
  *     b. 当此activity在栈顶时,触屏点击按home,back,menu键等都会触发此方法
  */
      public void onUserInteraction() {

      }

/**
  * 分析【2】:getWindow().superDispatchTouchEvent(ev)
  * a:getWindow()  得到  PhoneWindow
  * b. PhoneWindow.superDispatchTouchEvent(ev)源码
  */
  @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        // mDecor 是 DecorView类的对象。
        return mDecor.superDispatchTouchEvent(event);
    }

/**
*DecorView.superDispatchTouchEvent(en)源码
*/
 public boolean superDispatchTouchEvent(MotionEvent event) {
       //调用父类的dispatchTouchEvent方法。
       //DecorView继承FrameLayout,而FrameLayout继承ViewGroup。
       //所以最终调用到ViewGroup的dispatchTouchEvent方法。
        return super.dispatchTouchEvent(event);
 }

结论:事件要想从Activity传到View,我们重写Activity的dispatchTouchEvent()方法,必须调用super.dispatchTouchEvent(event)。

但是看到这里可能有个疑问,事件最终传到ViewGroup的dispatchTouchEvent()方法,并没有传到Activity使用的布局文件最外层我们自定义的ViewGorup里面啊(即RootGroupView)?上面不是说,图中的方法都是我们重写的方法吗?疑问是对的,上面说的也是对的。要解开疑问就需要看ViewGroup的dispatchTouchEvent()方法。

DOWN事件传到ViewGroup层

我们直接看ViewGroup的dispatchTouchEvent()方法的源码。

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }
        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;
            if (actionMasked == MotionEvent.ACTION_DOWN) {
                // 分析【1】mFirstTouchTarget初始化,即使 mFirstTouchTarget = null
                cancelAndClearTouchTargets(ev);
                // 分析【2】状态位重置,即 mGroupFlags = FLAG_DISALLOW_INTERCEPT = 0x80000;
                resetTouchState();
            }
            // 是否拦截标志位
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                // 分析【3】这个标志位(mGroupFlags )通过requestDisallowInterceptTouchEvent(boolean disallowIntercept)可以控制(请求父View不要拦截子View的事件),从而影响disallowIntercept 的结果。
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    // 分析【4】调用拦截方法,如果我们重写了onInterceptTouchEvent方法,调用的是我们重写的方法。
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    intercepted = false;
                }
            } else {
                intercepted = true;
            }
            if (intercepted || mFirstTouchTarget != null) {
                ev.setTargetAccessibilityFocus(false);
            }
            // CANCEL 事件的标志位。
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
            if (!canceled && !intercepted) { // 分析【5】事件没有被取消,没有被拦截。
                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;
                    removePointersFromTouchTargets(idBitsToAssign);
                    final int childrenCount = mChildrenCount;
                    if (newTouchTarget == null && childrenCount != 0) {
                        final float x = ev.getX(actionIndex);
                        final float y = ev.getY(actionIndex);
                        final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        // 分析【6】倒序遍历所有的子view
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = getAndVerifyPreorderedIndex(
                                    childrenCount, i, customOrder);
                            final View child = getAndVerifyPreorderedView(
                                    preorderedList, children, childIndex);
                            if (childWithAccessibilityFocus != null) {
                                if (childWithAccessibilityFocus != child) {
                                    continue;
                                }
                                childWithAccessibilityFocus = null;
                                i = childrenCount - 1;
                            }
                            // 分析【7】点击的位置是否在这个child子View上,没有就结束当前这次循环。
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }
                            //调用getTouchTarget方法去查找当前子View是否在mFirstTouchTarget.next这条target链中,
                            //如果存在则返回这个target,否则返回null。
                            newTouchTarget = getTouchTarget(child);
                            if (newTouchTarget != null) {
                                newTouchTarget.pointerIdBits |= idBitsToAssign;
                                break;
                            }
                            resetCancelNextUpFlag(child);
                            //分析【8】
                            //调用dispatchTransformedTouchEvent()方法将Touch事件传递给特定的子View
                            //该方法返回false--则说明子view未消耗点击事件,从而下面的newTouchTarget = addTouchTarget(child, idBitsToAssign)方法无法调用,mFirstTouchTarget则为null
                            //该方法返回true--则说明子view消耗点击事件,从而进入if区域,从而mFirstTouchTarget不为null。
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                mLastTouchDownTime = ev.getDownTime();
                                if (preorderedList != null) {
                                    for (int j = 0; j < childrenCount; j++) {
                                        if (children[childIndex] == mChildren[j]) {
                                            mLastTouchDownIndex = j;
                                            break;
                                        }
                                    }
                                } else {
                                    mLastTouchDownIndex = childIndex;
                                }
                                mLastTouchDownX = ev.getX();
                                mLastTouchDownY = ev.getY();
                                // 分析【9】给mFirstTouchTarget赋值,所有消耗点击事件的子View加入到mFirstTouchTarget链表中
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                //设置标志位,证明已经分发过
                                alreadyDispatchedToNewTouchTarget = true;
                                break; // 注【1】意这个 break。只要一个子View消费了这个事件,就跳出for循环。
                            }
                            ev.setTargetAccessibilityFocus(false);
                        }
                        if (preorderedList != null) preorderedList.clear();
                    }

                    if (newTouchTarget == null && mFirstTouchTarget != null) {
                        newTouchTarget = mFirstTouchTarget;
                        while (newTouchTarget.next != null) {
                            newTouchTarget = newTouchTarget.next;
                        }
                        newTouchTarget.pointerIdBits |= idBitsToAssign;
                    }
                }
            }
            // 分析【10】mFirstTouchTarget == null说明点击事件被拦截,或者子view没有消耗事件
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
                TouchTarget predecessor = null;
                TouchTarget target = mFirstTouchTarget;
                while (target != null) {
                    final TouchTarget next = target.next;
                    //分析【11】根据alreadyDispatchedToNewTouchTarget标志位 判断,如果已经分发了,则返回true
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        // 分析【12】如果事件被拦截,则变成CANCEL事件
                        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;
                }
            }
            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;
    }

分析【1】cancelAndClearTouchTargets(MotionEvent event)

private void cancelAndClearTouchTargets(MotionEvent event) {
        if (mFirstTouchTarget != null) {
            boolean syntheticEvent = false;
            if (event == null) {
                final long now = SystemClock.uptimeMillis();
                event = MotionEvent.obtain(now, now,
                        MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
                event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
                syntheticEvent = true;
            }
            for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
                resetCancelNextUpFlag(target.child);
                dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits);
            }
            clearTouchTargets();// mFirstTouchTarget == null  复位
            if (syntheticEvent) {
                event.recycle();
            }
        }
    }

    private void clearTouchTargets() {
        TouchTarget target = mFirstTouchTarget;
        if (target != null) {
            do {
                TouchTarget next = target.next;
                target.recycle();
                target = next;
            } while (target != null);
            mFirstTouchTarget = null; // mFirstTouchTarget == null  复位
        }
    }

最终在clearTouchTargets方法中将mFirstTouchTarget链表清空,以及把mFirstTouchTarget == null 复位。

分析【2】mGroupFlags标志位复位

 private void resetTouchState() {
        clearTouchTargets();
        resetCancelNextUpFlag(this);
        mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
        mNestedScrollAxes = SCROLL_AXIS_NONE;
    }

可以看到,mGroupFlags 标志位与 FLAG_DISALLOW_INTERCEPT = 0x80000 进行与或运算,所以mGroupFlags的值被复位为:0x80000。

resetTouchState方法是重置所有触摸状态以准备新的循环。

分析【3】是否拦截子View事件
其中FLAG_DISALLOW_INTERCEPT标志位其实就是requestDisallowInterceptTouchEvent(boolean disallowIntercept)设置的标志位用来阻止父类拦截点击事件。

public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
        if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
            return;
        }
        if (disallowIntercept) {// 拦截的标志位
            mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
        } else {
            mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
        }
        if (mParent != null) {
            mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
        }
    }

当我们在子View中调用 requestDisallowInterceptTouchEvent(true)请求父View不要拦截我的事件,从上面可以看出mGroupFlags 与FLAG_DISALLOW_INTERCEPT进行或运算在赋值给mGroupFlags,所以在分析【3】处,disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0 = true,所以intercepted标志为被赋值为flase,即不拦截事件。

注: 在子view中调用requestDisallowInterceptTouchEvent方法的时候,对于MotionEvent.ACTION_DOWN事件是无效的,因为MotionEvent.ACTION_DOWN事件会清除所有触摸状态

分析【4】调用onInterceptTouchEvent()事件拦截方法
disallowIntercept标志位为flase时,如果我们重写了onInterceptTouchEvent()方法,调用的是我们重写的方法,没有重写调用的是ViewGroup的onInterceptTouchEvent()。我们也可以看出,DOWN事件时,一定会调用onInterceptTouchEvent方法。

分析【5】不取消事件和不拦截事件
当不取消事件和不拦截事件时,会倒叙遍历当前ViewGroup的所有子View(分析[6]),并判断当前点击事件的位置时候在child的子View上?(分析[7])。如果不在就会结束当前的此次循环,遍历下一个子View。如果是就会调用dispatchTransformedTouchEvent()方法把事件传到当前的这个子View中(分析[8])。如果子View消费了事件了,即此处的dispatchTransformedTouchEvent()方法返回true。

分析【9】给mFirstTouchTarget赋值并标志该子View消费了事件
当子View消费事件,分析8处就返回true从而进入if语句,会执行addTouchTarget方法。

private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
        final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
        target.next = mFirstTouchTarget;
        mFirstTouchTarget = target;
        return target;
    }

从这个方法中我们可以看出,使用子View child生成一个TouchTarget对象。最终把这个对象赋值给mFirstTouchTarget。
注:这里先是把mFirstTouchTarget对象赋值给TouchTarget的对象target的next属性,在把target 赋值给mFirstTouchTarget对象。这里逻辑很妙,为什么?
1. 首先for循环是倒叙遍历的。
2. mFirstTouchTarget一开始是null的,把他赋值给target.next = mFirstTouchTarget;即target.next = null 。后面的while()语句中会用到target.next = null 作为判断条件。
所以结合这两点,在while()循环中,当target.next = null 时结束循环,也说明到了最后一个子View(倒叙添加到mFirstTouchTarget链表中的)。

表明有子View消费了事件alreadyDispatchedToNewTouchTarget = true;

注【1】结束for循环

当子View消费事件时,进入到if语句,最后执行break。我们都知道break有结束最近一层循环的作用。所以,当有一个子View消费事件时,就是执行break,即mFirstTouchTarget链表中其实只有一个子View。

分析[10]mFirstTouchTarget = null

mFirstTouchTarget 经过上面的分析我们知道,mFirstTouchTarget是在addTouchTarget()方法中被赋值的。所以mFirstTouchTarget = null 通常有两种情况,一:没有进入分析5处的if语句,即事件被拦截了。二:事件没有被拦截,但是没有子View消费事件,即没有进入分析8处的if语句。

分析[11]子View消费了事件

在while循环中,若alreadyDispatchedToNewTouchTarget = true 并且target == newTouchTarget 时直接返回ture,表明消费了事件。target由mFirstTouchTarget赋值过来,newTouchTarget由addTouchTarget()方法返回值赋值过来。为什么要加这样的逻辑判断呢? 假如不加这样的判断,首先在分析8处,该子View消费了事件了,即事件已经传到了子View,然后再进入这个whilei面在传递一次,即事件传递给子View传递了两次,这样逻辑就很难控制了。

分析[12]事件传递给子View
能执行到这里,即分析10处mFirstTouchTarget != null 分析11处if条件不成立。什么样的情况会这样执行呢?在DOWN事件时,分析8处消费了DOWN事件。即mFirstTouchTarget != null,当MOVE或UP事件来的时时候,拦截了MOVE或UP事件,即分析11处if语句的&&后面的条件不成立,这样就执行了分析12代码。这也CANCEL事件产生的过程。

事件传递的具体dispatchTransformedTouchEvent()方法源码
在分析8,分析10 ,分析12处都调用了dispatchTransformedTouchEvent()方法,不同地方传递的参数不同,参数不同方法执行过程也不相同结果不同。

private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        final boolean handled;
        final int oldAction = event.getAction();
        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
        // 【CANCEL事件产生】CANCEL事件产生的地方
            event.setAction(MotionEvent.ACTION_CANCEL);
            if (child == null) {
               // 【CANCEL事件产生,传递到父View】
                handled = super.dispatchTouchEvent(event);
            } else {
                // 【CANCEL事件产生,传递到子View】
                handled = child.dispatchTouchEvent(event);
            }
            event.setAction(oldAction);
            return handled;
        }
        final int oldPointerIdBits = event.getPointerIdBits();
        final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
        if (newPointerIdBits == 0) {
            return false;
        }
        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);
        }
        if (child == null) {
            // 【调用父View的方法】子View为null,调用父View的dispatchTouchEvent()方法,即View的dispatchTouchEvent()方法
            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());
            }
            // 【事件传递到子View】子View不为null,将调用子View 的dispatchTouchEvent的方法。即事件传递到子View中去。
            handled = child.dispatchTouchEvent(transformedEvent);
        }
        transformedEvent.recycle();
        return handled;
    }
  • 在分析【8】处,cancel = false , child !=null 所以执行到*【事件传递到子View】*,即事件传递到子Viwe child的dispatchTouchEvent方法中。
  • 在分析【10】处,cancel = false,child = null,所以会执行*【调用父View的方法】*,ViewGroup继承View的,即事件到Viewd的dispatchTouchEvent方法中。
  • 在分析【12】处,在上面说的那种情况下,cancel = true , child != null,所以执行到*【CANCEL事件产生,传递到子View】*,子View child的dispatchTouchEvent方法接受的时CANCEL事件 。

到这里我们能解开上面的疑问了。我们在Activtiy布局加载中说到,Activity使用的布局文件,最终会由LayoutInfalter转变成View添加到mDecor中成为一个子View。所以当DOWN事件有Activity调用super.dispatchTouchEvent()传到ViewGroup的dispatchTouchEvent方法,在这个方法里,在传递到布局文件中的最外层的View中(测试代码的RootViewGroup中)。

结论:事件从Activity传递到布局文件中的View的过程如下:Activity.dispatchTouchEvent()->super.dispatchTouchEvent()
->PhoneWindow.superDispatchTouchEvent()-> DecorView.superDispatchTouchEvent()->super.dispatchTouchEvent(event)(ViewGroup)->布局文件中的View

3.RootViewGroup的dispatchTouchEvent()返回true,事件消费
经过上面的分析,我们知道了DOWN事件从Activity传到自定义RootViewGroup的dispatchTouchEvent()方法中过程。图中说到RootViewGroup的dispatchTouchEvent()返回true时,事件消费了,为什么?细心的同学可能已经知道答案了。我们看Activity的dispatchTouchEvent()方法的源码:

 public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {// 分析【1】
            return true;
        }
        return onTouchEvent(ev);
    }

当RootViewGroup的dispatchTouchEvent()返回true时, 分析【1】处的getWindow().superDispatchTouchEvent(ev)就是true,所以if成立,即返回true,方法执行结束。

4.RootViewGroup的dispatchTouchEvent()返回false,事件传到我们自定义的Activity的onTouchEvent()方法
为什么?我们还是需要看Activity的dispatchTouchEvent()方法的源码。当RootViewGroup的dispatchTouchEvent()返回false时,getWindow().superDispatchTouchEvent(ev)就时false,if条件不成立,不进入if语句,所以会执行onTouchEvent()方法,我们重写了Activity的onTouchEvent()方法,所以调用的我们重写的onTouchEvent()方法。

5.RootViewGroup的dispatchTouchEvent()返回默认,即调用super.dispatchTouchEvent(),事件传到我们自定义RootViewGroup的onInterceptTouchEvent方法
为什么?我们知道事件从Activity传到RootViewGroup,经过了PhoneWindow和ViewGroup,当传到RootViewGroup的dispatchTouchEvent()后,我们调用super.dispatchTouchEvent()方法,RootViewGroup是继承ViewGroup的,所以事件又回到了ViewGroup的dispatchTouchEvent()方法中。我们在上面分析了DOWN事件是一定会调用onInterceptTouchEvent()方法的,所以会传到我们自定义RootViewGroup的onInterceptTouchEvent()方法中。

6.RootViewGroup的onInterceptTouchEvent()方法返回false或默认(super.onInterceptTouchEvent()),事件传到自定义RootViewGroup的子View,即SubView的dispatchTouchEvent()方法
为什么?首先我们看ViewGroup的onInterceptTouchEvent()方法的源码返回的是false,所以我们自定RootViewGroup的onInterceptTouchEvent()方法返回false或默认效果是一样的。onInterceptTouchEvent()返回false,表示不拦截事件,那么会执行到ViewGroup的dispatchTouchEvent()中的分析【5,6,7,8】处,在分析【8】处调用dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,View child, int desiredPointerIdBits)方法,其中参数cancel =false , child != null,所以会执行到dispatchTransformedTouchEvent()方法中的*【事件传递到子View】*处,即事件就传了RootViewGroup的子View,即SubView的dispatchTouchEvent()中去了。

7.RootViewGroup的onInterceptTouchEvent()方法返回true,事件传到RootViewGroup的onTouchEvent()方法
为什么?我们在分析ViewGroup的dispatchTouchvent()方法时提到,onTouchEvent()方法返回true,即拦截了事件。所以mFirstTouchTarget = null,代码会执行到分析【10】处的if(mFirstTouchTarget == null)里面调用
dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,View child, int desiredPointerIdBits)方法, 其中参数 cancel =false , child = null ,所以dispatchTransformedTouchEvent方法会执行到*【调用父View的方法】*处,而ViewGroup继承View,所以事件传递到View的dispatchTouchEvent()方法中。疑问: 既然事件传到了View的dispatchTouchEvent()方法中,标题为什么说事件传到RootViewGroup的onTouchEvent()方法中去了呢?要知道答案就需要看View的dispatchTouchEvent()方法的源码。

DOWN事件传到View层

我们看View的dispatchTouchEvent()方法的源码:

public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.isTargetAccessibilityFocus()) {
            if (!isAccessibilityFocusedViewOrHost()) {
                return false;
            }
            event.setTargetAccessibilityFocus(false);
        }
        boolean result = false;
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }
        final int actionMasked = event.getActionMasked();
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            stopNestedScroll();
        }
        //分析【1】当前View是否没被遮住等
        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            ListenerInfo li = mListenerInfo;
            // 分析【2】调用onTouch方法,它其实就是OnTouchListener接口的方法
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
            // 分析【3】
            //onTouch方法返回true,则不执行onTouchEvent(event)方法
            //onTouch方法返回false,则执行onTouchEvent(event)方法
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }
        if (!result && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }
        if (actionMasked == MotionEvent.ACTION_UP ||
                actionMasked == MotionEvent.ACTION_CANCEL ||
                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
            stopNestedScroll();
        }
        return result;
    }

分析【1】
onFilterTouchEventForSecurity(event)判断当前View是否没被遮住,如果没有被遮挡住,则执行if语句块中代码。

分析【2】
ListenerInfo是View的静态内部类,里面是一些回调接口,比如:OnClickListener,OnLongClickListener等等。这个if()判断比较长,li是ListenerInfo的对象,已经初始化过了,必然不为null,li.mOnTouchListener是否为null呢?全局搜一下,在哪里初始化或者赋值。在View中搜索到如下代码:

public void setOnTouchListener(OnTouchListener l) {
        getListenerInfo().mOnTouchListener = l;
    }

    ListenerInfo getListenerInfo() {
        if (mListenerInfo != null) {
            return mListenerInfo;
        }
        mListenerInfo = new ListenerInfo();
        return mListenerInfo;
    }
  • 设置我们的view (SunView)setOnTouchListener(OnTouchListener l)方法后,li.mOnTouchListener !=null ,则执行if语句块中代码。反之,如果不设置setOnTouchListener方法即li.mOnTouchListener ==null ,则不执行if语句块中代码,则result=false,onTouchEvent()方法将被调用。
  • 接着通过位与运算确定控件View(SunView)是不是enabled的,默认控件都是enabled的,也就是说,如果你调用一个view,设置成view.setEnabled(false),则view的onTouch方法将不会被触发,onTouchEvent方法则不受影响(因为result=false)。
  • 调用li.mOnTouchListener.onTouch(this, event),如果onTouch方法返回true,则result=true,就不执行onTouchEvent(event)方法,反之,则执行onTouchEvent(event)方法。所以一般如果我们在自己的view中设置了setOnTouchListener方法后,并且返回值设置成true后,则当前view就接受不到onTouchEvent(event)方法。

分析【3】
result = false 就会调用onInterceptTouchEvent()方法。

通过对View的dispatchTouchEvent()方法学习,我能解开上面的疑问了。当RootViewGroup的onInterceptTouchEvent()方法返回true,事件先是传递到View的dispatchTouchEvent()方法,在View的dispatchTouchEvent()方法中调用了onTouchEvent()方法,ViewGroup继承View,而RootViewGroup继承ViewGroup,并且重写了onTouchEvent()方法,所以调用的是RootViewGroup重写的onTouchEvent()方法,即事件传递到了RootViewGroup的onTouchEvent()方法中。

8.RootViewGroup的onTouchEvent()方法返回false或默认(即调用super.onTouchEvent()),事件传递到Activity的onTouchEvent()方法中
为什么?首先我们看ViewGroup没有重写onTouchEvent()方法我们直接看View的 onTouchEvent(MotionEvent event)方法,默认是返回false的,所以返回false和默认效果是一样的。当RootViewGroup的onTouchEvent()方法返回false,经过一系列的回传,Activity的dispatchTouchEvent()方法中的getWindow().superDispatchTouchEvent(ev)为false,if()条件不成立,所以会执行onTouchEvent()方法,所以.RootViewGroup的onTouchEvent()方法返回false或默认(即调用super.onTouchEvent()),事件传递到Activity的onTouchEvent()方法中。

9.RootViewGroup的onTouchEvent()方法返回true,事件消费
为什么?当RootViewGroup的onTouchEvent()返回true,经过一系列的回传,Activity的dispatchTouchEvent()方法中的getWindow().superDispatchTouchEvent(ev)为true,返回true,方法执行结束。

10.SubView的dispatchTouchEvent()方法返回true,事件消费
为什么?原理和RootViewGroup的原理一样,当SubView的dispatchTouchEvent()返回true,经过一系列的回传,Activity的dispatchTouchEvent()方法中的getWindow().superDispatchTouchEvent(ev)为true,返回true,方法执行结束。

11.SubView的dispatchTouchEvent()方法返回false,事件将传递到RootViewGroup的onTouchEvent()方法
为什么?当事件传递到ViewGroup的dispatchTouchEvent()方法的分析【8】处,调用dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,View child, int desiredPointerIdBits)方法将事件传递到SubView的dispatchTouchEvent()的方法中,SubView的dispatchTouchEvent()的方法返回false,即ViewGroup的dispatchTouchEvent()方法的分析【8】处的if条件不成立,则mFirstTouchTarget = null,则会执行到分析【10】处,将事件传递给View的dispatchTouchEvent()方法,而dispatchTouchEvent()方法中调用onTouchEvent()方法。ViewGroup继承View,RootViewGroup继承ViewGorup,所以View的dispatchTouchEvent()方法中调用的onTouchEvent()方法其实是RootViewGroup重写的onTouchEvent()方法,所以SubView的dispatchTouchEvent()方法返回false,事件将传递到RootViewGroup的onTouchEvent()方法。

12.SubView的dispatchTouchEvent()方法返回默认,即调用super.dispatchTouchEvent(),事件将传递到SubView的onTouchEvent()方法
为什么?事件传递到SubView的dispatchTouchEvent()后,调用super.dispatchTouchEvent(),事件会传递到View的dispatchTouchEvent()方法,前面学了View的dispatchTouchEvent(),里面会调用onTouchEvent()方法,而SubView重写了View的的onTouchEvent()方法。所以SubView的dispatchTouchEvent()方法返回默认,即调用super.dispatchTouchEvent(),事件将传递到SubView的onTouchEvent()方法。
13.SubView的onTouchEvent()方法返回true,事件消费
为什么?原理和RootViewGroup的原理一样,当SubView的onTouchEvent()方法返回true,经过一系列的回传,Activity的dispatchTouchEvent()方法中的getWindow().superDispatchTouchEvent(ev)为true,返回true,方法执行结束。
14.SubView的onTouchEvent()方法返回false或默认(即调用super.onTouchEvent()),事件将传递到RootViewGroup的onTouchEvent()方法。
为什么?首先我们看View的 onTouchEvent(MotionEvent event)方法,默认是返回false的,所以返回false和默认效果是一样的。当SubView的onTouchEvent()方法返回false,经过回传,则ViewGroup的dispatchTouchEvent()方法的分析【8】处为false,if条件不成立,所以mFirstTouchTarget = null ,执行到分析【10】处调用dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,View child, int desiredPointerIdBits)方法,执行到*【调用父View的方法】*处。事件传递到View的diapstchTouchEvent()方法,调用onTouchEvent()方法。ViewGroup继承View,RootViewGroup继承ViewGroup并重写了onTouchEvent()方法,所以SubView的onTouchEvent()方法返回false或默认(即调用super.onTouchEvent()),事件将传递到RootViewGroup的onTouchEvent()方法。

到此,我们从源码的角度学习完了View的DOWN事件的传递机制,并总结出了图中的每一种走向。

10-07 16:04