从源码角度分析View事件分发

Andorid事件分发

  • 引言
    • 源码分析

引言

View分发是自定义View上的必经之路,也是比较难的一部分。今天我们从源码的角度来分析一下View的分发机制

源码分析

从源码角度分析View事件分发_第1张图片
(ps:图片来源于hwldzh)
从图片来看 很难看到时间分发的核心在哪里,想了解一个东西流程以及过程最好的办法就是看他整个事件的过程流程以及思路,下面我们开始分析。

1.View,ViewGroup事件分发
1.Touch事件分发中只有两个主角:ViewGroup和View。ViewGroup包含onInterceptTouchEvent、dispatchTouchEvent、onTouchEvent三个相关事件。View包含dispatchTouchEvent、onTouchEvent两个相关事件。其中ViewGroup又继承于View。

2.ViewGroup和View组成了一个树状结构,根节点为Activity内部包含的一个ViwGroup。

3.触摸事件由Action_Down、Action_Move、Aciton_UP组成,其中一次完整的触摸事件中,Down和Up都只有一个,Move有若干个,可以为0个。

4.当Acitivty接收到Touch事件时,将遍历子View进行Down事件的分发。ViewGroup的遍历可以看成是递归的。分发的目的是为了找到真正要处理本次完整触摸事件的View,这个View会在onTouchuEvent结果返回true。

5.当某个子View返回true时,会中止Down事件的分发,同时在ViewGroup中记录该子View。接下去的Move和Up事件将由该子View直接进行处理。由于子View是保存在ViewGroup中的,多层ViewGroup的节点结构时,上级ViewGroup保存的会是真实处理事件的View所在的ViewGroup对象:如ViewGroup0-ViewGroup1-TextView的结构中,TextView返回了true,它将被保存在ViewGroup1中,而ViewGroup1也会返回true,被保存在ViewGroup0中。当Move和UP事件来时,会先从ViewGroup0传递至ViewGroup1,再由ViewGroup1传递至TextView。

6.当ViewGroup中所有子View都不捕获Down事件时,将触发ViewGroup自身的onTouch事件。触发的方式是调用super.dispatchTouchEvent函数,即父类View的dispatchTouchEvent方法。在所有子View都不处理的情况下,触发Acitivity的onTouchEvent方法。

7.onInterceptTouchEvent有两个作用:1.拦截Down事件的分发。2.中止Up和Move事件向目标View传递,使得目标View所在的ViewGroup捕获Up和Move事件。

2.1 事件分发的流程
从你手点击屏幕的那一刻起事件会传递到当前View所在的Activity中由Activity
的dispathOnTouchEvent进行分发
先来看看dispathOnTouchEvent的源码

public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        onUserInteraction();
    }
    if (getWindow().superDispatchTouchEvent(ev)) {
        return true;
    }
    return onTouchEvent(ev);
}

我们看到当前的代码

getWindow().superDispathTouChEvent(ev)

首先调用了getWindow(). superDispatchTouchEvent方法,返回true表示事件被消耗掉了;返回false表示事件交给Activity的onTouchEvent方法处理。
这段代码的调用了 getWindow 下面的分发,Window是一个类。在A浓度日的中
PhoneWindow 是Window的唯一实现类。
下面是Window类中的方法

public boolean superDispatchTouchEvent(MotionEvent event) {
    return mDecor.superDispatchTouchEvent(event);
}

该类调用了mDecor.superDispatchTouchEvent(event); 方法 mDecor是什么?
这里的mDecor是DecorView类型,DecorView是activity窗口的根视图

我们来看看mDecor.superDispatchTouchEvent(event);又实现了什么内容?

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

调用了super.dispatchTouchEvent(event); 方法 DecorView的父类就是ViewGroup
所以这一块是调用了ViewGroup的 dispathTouchEvent(event)方法,所有已经传递到顶级的ViewGroup中了

2.2 ViewGroup的分发
下面我看一看ViewGroup中分发代码重要部分

final boolean intercepted; //记录是否被拦截
   //当前事件为ACTION_DOWN时事件时,或者 mFirstTouchTarget 不为空(mFirstTouchTarget 下文会提到)
    if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) {
        //由于事件为ACTION_DOWN时,重置了mGroupFlags,所以一定会调onInterceptTouchEvent方法。
        final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
        if (!disallowIntercept) {
            //调用onInterceptTouchEvent方法,判断是否需要拦截该事件
            intercepted = onInterceptTouchEvent(ev); 
            ev.setAction(action); 
        } else {
            intercepted = false;
        }
    } else {
        intercepted = true;
    }

mFirstTouchTarget != null,是什么?用来记录当前事件是否被子View消费了,
或者之前的某次事件已经经由此ViewGroup派发给children后被处理掉了(PS:经过一次处理之后以后的每次分发都交由上个处理的View 进行 事件的处理)
由于事件为ACTION_DOWN事件时,重置mGroupFlages。字面意思来看用户
按下这一刻这个参数被清空了。其实在这段代码之前还有一段 清空代码!来看看

 // Handle an initial down.
   if (actionMasked == MotionEvent.ACTION_DOWN) { // 一堆touch事件(从按下到松   手)中的第一个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(); // 作为新一轮的开始,reset所有相关的状态
   }

2.2.1ViewGroup进行拦截

 intercepted = onInterceptTouchEvent(ev);

这段代码是ViewGroup进行拦截时候进入的方法
我们看看这其中的代码片段

if (!canceled && !intercepted) {
    //当前为 true 所以不会进入到这里
    ...省略部分代码下文展出完整代码
}
if (mFirstTouchTarget == null) {
    // 没有children处理则派发给自己处理
    // No touch targets so treat this as an ordinary view.
    handled = dispatchTransformedTouchEvent(ev, canceled, null,
            TouchTarget.ALL_POINTER_IDS);
} else {
    ...省略
}

mFirstTouchTarget 为空所以 这个事件没有被子View消费过。所以自己进行处理

其if分支中调用了
dispatchTransformedTouchEvent(ev, canceled, null,TouchTarget.ALL_POINTER_IDS);
注第三个参数为null 

重要部分还是在最后面

private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
        View child, int desiredPointerIdBits) {
    final boolean handled;
		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);
		 }
}

在这里判断了 child 是否为空 所以进入了if分支调用了
super.dispatchTouchEvent(transformedEvent); 自己进行消费

 public boolean dispatchTouchEvent(MotionEvent event) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }
 
        if (onFilterTouchEventForSecurity(event)) { // 一般都成立
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) ==       ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) { // 先在ENABLED状态下尝试调用onTouch方法
                return true; // 如果被onTouch处理了,则直接返回true
            }
            // 从这里我们可以看出,当你既设置了OnTouchListener又设置了OnClickListener,那么当前者返回true的时候,
            // onTouchEvent没机会被调用,当然你的OnClickListener也就不会被触发;另外还有个区别就是onTouch里可以
            // 收到每次touch事件,而onClickListener只是在up事件到来时触发。
            if (onTouchEvent(event)) {
                return true;
            }
        }
 
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }
        return false; // 上面的都没处理,则返回false
  }

li.mOnTouchListener != null 这行代码来判断的了当前的View是否设置了
OnTouchListener 并且 OnTouch 中反回了true
true说明了 这里不会再执行View的 onTouchEvent 方法 反之去执行
所以从源码来分析
OnTouch 优先级 > onTouchEvent 优先级
那我们的onClick 事件的 当然 他的级别是最低的
OnTouch 优先级 > onTouchEvent 优先级 > onClick优先级
2.2.2 ViewGroup不进行拦截 false
intercepted 为false
所以当前进入到


public boolean dispatchTouchEvent(MotionEvent ev) {
if (!canceled && !intercepted) {// 没取消也不拦截,即是个有效的touch事件
   if (actionMasked == MotionEvent.ACTION_DOWN // 第一个手指down
             || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN) // 接下来的手指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 View[] children = mChildren;

             final boolean customOrder = isChildrenDrawingOrderEnabled();
             // 从最后一个向第一个找
             for (int i = childrenCount - 1; i >= 0; i--) {
                 final int childIndex = customOrder ?
                         getChildDrawingOrder(childrenCount, i) : i;
                 final View child = children[childIndex];
                 if (!canViewReceivePointerEvents(child)
                         || !isTransformedTouchPointInView(x, y, child, null)) {
                     continue; // 不满足这2个条件直接跳过,看下一个child
                 }
                 
                 // child view能receive touch事件而且touch坐标也在view边界内

                 newTouchTarget = getTouchTarget(child);// 查找child对应的TouchTarget
                 if (newTouchTarget != null) { // 比如在同一个child上按下了多跟手指
                     // 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; // newTouchTarget已经有了,跳出for循环
                 }

                 resetCancelNextUpFlag(child);
                 // 将此事件交给child处理
                 // 有这种情况,一个手指按在了child1上,另一个手指按在了child2上,以此类推
                 // 这样TouchTarget的链就形成了
                 if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                     // Child wants to receive touch within its bounds.
                     mLastTouchDownTime = ev.getDownTime();
                     mLastTouchDownIndex = childIndex;
                     mLastTouchDownX = ev.getX();
                     mLastTouchDownY = ev.getY();
                     // 如果处理掉了的话,将此child添加到touch链的头部
                     // 注意这个方法内部会更新 mFirstTouchTarget
                     newTouchTarget = addTouchTarget(child, idBitsToAssign);
                     alreadyDispatchedToNewTouchTarget = true; // down或pointer_down事件已经被处理了
                     break; // 可以退出for循环了。。。
                 }
             }
         }

         // 本次没找到newTouchTarget但之前的mFirstTouchTarget已经有了
         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;
             }
             // while结束后,newTouchTarget指向了最初的TouchTarget
             newTouchTarget.pointerIdBits |= idBitsToAssign;
         }
     }
 }

这段代码主要讲解了遍历自己的子View 将事件分发下去
对于子View 调用了
(dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) 方法
当前的第三个参数 为自己的子View 所以传递了 child 参数 在上文中ViewGroup也调用同样的方法 不给过第三个参数为 null

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);
 }
 当child不为空是 调用了 child.dispatchTouchEvent(transformedEvent)

public boolean dispatchTouchEvent(MotionEvent event) {
     if (mInputEventConsistencyVerifier != null) {
         mInputEventConsistencyVerifier.onTouchEvent(event, 0);
     }

     if (onFilterTouchEventForSecurity(event)) { // 一般都成立
         //noinspection SimplifiableIfStatement
         ListenerInfo li = mListenerInfo;
         if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
                 && li.mOnTouchListener.onTouch(this, event)) { // 先在ENABLED状态下尝试调用onTouch方法
             return true; // 如果被onTouch处理了,则直接返回true
         }
         // 从这里我们可以看出,当你既设置了OnTouchListener又设置了OnClickListener,那么当前者返回true的时候,
         // onTouchEvent没机会被调用,当然你的OnClickListener也就不会被触发;另外还有个区别就是onTouch里可以
         // 收到每次touch事件,而onClickListener只是在up事件到来时触发。
         if (onTouchEvent(event)) {
             return true;
         }
     }

     if (mInputEventConsistencyVerifier != null) {
         mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
     }
     return false; // 上面的都没处理,则返回false
}

当dispatchTransformedTouchEvent方法返回true时,表示事件由该子View消耗了,所以addTouchTarget方法就会被执行。

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

2.3 View对事件的分发
在dispatchTransformedTouchEvent方法中 child不为空就表示当前是一个 View
调用 child.dispatchTouchEvent(transformedEvent); 方法

private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
        View child, int desiredPointerIdBits) {
    final boolean handled;
		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);
		 }
}

View 的dispathTouchEvent代码在下面

下面贴上三个重要方法的源码+加注释
ViewGroup 的 dispatchTouchEvent

 public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }
 
        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) { // view没有被遮罩,一般都成立
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;
 
            // Handle an initial down.
            if (actionMasked == MotionEvent.ACTION_DOWN) { // 一堆touch事件(从按下到松手)中的第一个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(); // 作为新一轮的开始,reset所有相关的状态
            }
 
            // Check for interception.
            final boolean intercepted; // 检查是否要拦截
            if (actionMasked == MotionEvent.ACTION_DOWN // down事件
                    || mFirstTouchTarget != null) { // 或者之前的某次事件已经经由此ViewGroup派发给children后被处理掉了
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) { // 只有允许拦截才执行onInterceptTouchEvent方法
                    intercepted = onInterceptTouchEvent(ev); // 默认返回false,不拦截
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    intercepted = false; // 不允许拦截的话,直接设为false
                }
            } else {
                // There are no touch targets and this action is not an initial down
                // so this view group continues to intercept touches.
                // 在这种情况下,actionMasked != ACTION_DOWN && mFirstTouchTarget == null
                // 第一次的down事件没有被此ViewGroup的children处理掉(要么是它们自己不处理,要么是ViewGroup从一
                // 开始的down事件就开始拦截),则接下来的所有事件
                // 也没它们的份,即不处理down事件的话,那表示你对后面接下来的事件也不感兴趣
                intercepted = true; // 这种情况下设置ViewGroup拦截接下来的事件
            }
 
            // Check for cancelation.
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL; // 此touch事件是否取消了
 
            // Update list of touch targets for pointer down, if needed.
            // 是否拆分事件,3.0(包括)之后引入的,默认拆分
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
            TouchTarget newTouchTarget = null; // 接下来ViewGroup判断要将此touch事件交给谁处理
            boolean alreadyDispatchedToNewTouchTarget = false;
            if (!canceled && !intercepted) { // 没取消也不拦截,即是个有效的touch事件
                if (actionMasked == MotionEvent.ACTION_DOWN // 第一个手指down
                        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN) // 接下来的手指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 View[] children = mChildren;
 
                        final boolean customOrder = isChildrenDrawingOrderEnabled();
                        // 从最后一个向第一个找
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = customOrder ?
                                    getChildDrawingOrder(childrenCount, i) : i;
                            final View child = children[childIndex];
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                continue; // 不满足这2个条件直接跳过,看下一个child
                            }
                            
                            // child view能receive touch事件而且touch坐标也在view边界内
 
                            newTouchTarget = getTouchTarget(child);// 查找child对应的TouchTarget
                            if (newTouchTarget != null) { // 比如在同一个child上按下了多跟手指
                                // 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; // newTouchTarget已经有了,跳出for循环
                            }
 
                            resetCancelNextUpFlag(child);
                            // 将此事件交给child处理
                            // 有这种情况,一个手指按在了child1上,另一个手指按在了child2上,以此类推
                            // 这样TouchTarget的链就形成了
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                // Child wants to receive touch within its bounds.
                                mLastTouchDownTime = ev.getDownTime();
                                mLastTouchDownIndex = childIndex;
                                mLastTouchDownX = ev.getX();
                                mLastTouchDownY = ev.getY();
                                // 如果处理掉了的话,将此child添加到touch链的头部
                                // 注意这个方法内部会更新 mFirstTouchTarget
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true; // down或pointer_down事件已经被处理了
                                break; // 可以退出for循环了。。。
                            }
                        }
                    }
 
                    // 本次没找到newTouchTarget但之前的mFirstTouchTarget已经有了
                    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;
                        }
                        // while结束后,newTouchTarget指向了最初的TouchTarget
                        newTouchTarget.pointerIdBits |= idBitsToAssign;
                    }
                }
            }
            // 非down事件直接从这里开始处理,不会走上面的一大堆寻找TouchTarget的逻辑
            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                // 没有children处理则派发给自己处理
                // 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) { // 遍历TouchTarget形成的链表
                    final TouchTarget next = target.next;
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true; // 已经处理过的不再让其处理事件
                    } else {
                        // 取消child标记
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        // 如果ViewGroup从半路拦截了touch事件则给touch链上的child发送cancel事件
                        // 如果cancelChild为true的话
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            handled = true; // TouchTarget链中任意一个处理了则设置handled为true
                        }
                        if (cancelChild) { // 如果是cancelChild的话,则回收此target节点
                            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) {
                // 取消或up事件时resetTouchState
                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; // 返回处理的结果
    }

dispatchTransformedTouchEvent


  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;
    }

View的dispatchTouchEvent

   public boolean dispatchTouchEvent(MotionEvent event) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }
 
        if (onFilterTouchEventForSecurity(event)) { // 一般都成立
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) { // 先在ENABLED状态下尝试调用onTouch方法
                return true; // 如果被onTouch处理了,则直接返回true
            }
            // 从这里我们可以看出,当你既设置了OnTouchListener又设置了OnClickListener,那么当前者返回true的时候,
            // onTouchEvent没机会被调用,当然你的OnClickListener也就不会被触发;另外还有个区别就是onTouch里可以
            // 收到每次touch事件,而onClickListener只是在up事件到来时触发。
            if (onTouchEvent(event)) {
                return true;
            }
        }
 
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }
        return false; // 上面的都没处理,则返回false

总结
我们大体来总结一下View的事件分发
首先会进入dispatchTouchEvent方法 进行分发 ->进行判断当前事件拦截->onInterceptTouchEvent(根据当前事件有没有被子View 进行过消费)->拦截
true(判断当前VIew是否进行了OnTouchListener设置 并且通过onTouch 的值判断OnTouch事件是触发) ->不拦截 继续分析循环分发 调用 dispatchTransformedTouchEvent 方法

Andorid知识星球,欢迎大家关注!
从源码角度分析View事件分发_第2张图片

本文部分参考
https://blog.csdn.net/brastom/article/details/52875837

你可能感兴趣的:(Android)