Android事件分发机制学习笔记(ViewGroup篇)

本文是学习Android事件分发机制的学习笔记,一是为了巩固学习成果,加深印象;二是为了方便以后查阅。


Activity对事件的分发过程

Activity#dispatchTouchEvent()开始看起:

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

首先对ACTION_DOWN 事件进行了特殊判断,调用onUserInteraction() ,跟进这个方法,会发现是一个空方法:

public void onUserInteraction() {
}

不去管它,接下来Activity会通过getWindow() 获得自己所属的Window 进行分发,Window 是个抽象类,用来控制顶级View的外观和行为策略,它的唯一实现类是PhoneWindow 。那么PhoneWindow 是如何处理点击事件的,PhoneWindow#superDispatchTouchEvent() 如下所示:

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

很简单,直接传递给了mDecor ,这个mDecor 就是当前窗口最顶层的DecorView

// This is the top-level view of the window, containing the window decor.
private DecorView mDecor;

跟进DecorView#superDispatchTouchEvent() :

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

居然是调用父类的dispatchTouchEvent() 方法,DecorView 的父类是FrameLayout ,继续跟进查看,发现FrameLayout 并没有这个方法,那就继续向上追,FrameLayout 的父类是ViewGroup ,也就是说,触摸事件经过层层传递,最终传递到ViewGroup#dispatchTouchEvent() 方法,至此,事件已经传递到视图的顶级View了。


ViewGroup对事件的分发过程

接下来是重头戏了...上代码ViewGroup#dispatchTouchEvent() ...

public boolean dispatchTouchEvent(MotionEvent ev) {
    // 调试用,不去管它
    if (mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
    }

    // 辅助功能,有些用户由于视力上、身体上、年龄上使他们不能接受语音或者视觉信息
    // 不是重点,也不去管它
    if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
        ev.setTargetAccessibilityFocus(false);
    }

    boolean handled = false;
    // onFilterTouchEventForSecurity(ev),触摸事件安全过滤
    // 具体实现:当窗口被遮挡,返回false,丢弃触摸事件;未被遮挡,返回true    
    if (onFilterTouchEventForSecurity(ev)) {
        // 没有被遮挡
        final int action = ev.getAction();
        final int actionMasked = action & MotionEvent.ACTION_MASK;

        // Handle an initial down.
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // 如果是Down事件,则重置所有之前保存的状态,因为这是事件序列的开始
            // mFirstTouchTarget会被设为Null
            cancelAndClearTouchTargets(ev);
            // 重置FLAG_DISALLOW_INTERCEPT
            resetTouchState();
        }

        // 检测是否拦截
        final boolean intercepted;
        if (actionMasked == MotionEvent.ACTION_DOWN
                || mFirstTouchTarget != null) {
            // 标记事件不允许被拦截,默认为false
            // 可以由requestDisallowInterceptTouchEvent方法来设置
            // 设置为true,ViewGroup将无法拦截Down以外的点击事件
            final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
            if (!disallowIntercept) {
                // 调用onInterceptTouchEvent(ev)方法,询问自己是否要拦截事件
                // ViewGroup的onInterceptTouchEvent(ev)方法默认返回false
                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);
            }

            // 通过标记和Action检查Cancel,将结果赋值给局部变量canceled
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

            // split标记是否需要将事件分发给多个子View,默认为true
            // 可通过setMotionEventSplittingEnabled()方法设置
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
          
            // 如果没取消也没拦截,进入执行语句中
            if (!canceled && !intercepted) {
              
            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;
                // 判断newTouchTarget为Null,且ChildrenCount不为0
                if (newTouchTarget == null && childrenCount != 0) {
                    final float x = ev.getX(actionIndex);
                    final float y = ev.getY(actionIndex);
                    // 寻找可以处理触摸事件的子View
                    // 通过buildTouchDispatchChildList()方法构建子View的List集合preorderedList
                    final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                    final boolean customOrder = preorderedList == null
                            && isChildrenDrawingOrderEnabled();
                    final View[] children = mChildren;
                    // 倒序遍历所有的子View
                    for (int i = childrenCount - 1; i >= 0; i--) {
                        final int childIndex = getAndVerifyPreorderedIndex(
                                childrenCount, i, customOrder);
                        final View child = getAndVerifyPreorderedView(
                                preorderedList, children, 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;
                        }

                        // 同时满足两种情况下子View可以接收事件的分发
                        // canViewReceivePointerEvents()方法会判断子View是否可见和是否在播放动画
                        // isTransformedTouchPointInView()方法会判断触摸事件坐标是否在子View内
                        if (!canViewReceivePointerEvents(child)
                                || !isTransformedTouchPointInView(x, y, child, null)) {
                            ev.setTargetAccessibilityFocus(false);
                            continue;
                        }

                        // 查找当前子View是否在mFirstTouchTarget中存储
                        // mFirstTouchTarget是一种单链表结构
                        // 找不到则返回Null
                        newTouchTarget = getTouchTarget(child);
                        if (newTouchTarget != null) {
                            // newTouchTarget不为Nul,说明已经找到接收的View了,break跳出for循环
                            newTouchTarget.pointerIdBits |= idBitsToAssign;
                            break;
                        }
                      
                        resetCancelNextUpFlag(child);
                      
                        // 没有跳出循环,说明我们找到的Child并没有在mFirstTouchTarget中
                        // 调用dispatchTransformedTouchEvent()方法
                        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();
                            // 将child赋值给mFirstTouchTarget
                            newTouchTarget = addTouchTarget(child, idBitsToAssign);
                            // alreadyDispatchedToNewTouchTarget赋值为true,跳出循环
                            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();
                }

                // 没有找到可以接收事件的子View,并且之前的mFirstTouchTarget不为空
                // 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;
                    }
                    newTouchTarget.pointerIdBits |= idBitsToAssign;
                }
            }
        }

        if (mFirstTouchTarget == null) {
            // 如果mFirstTouchTarget为null
            // 调用dispatchTransformedTouchEvent()方法
            // 第三个参数为null,会调用super.dispatchTouchEvent()方法
            // 将当前ViewGroup当做普通的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;
}

事件拦截

intercepted 用来标记ViewGroup 是否拦截事件,当事件为MotionEvent.ACTION_DOWN 或者mFirstTouchTarget!=null 时,if 判断成立,然后判断disallowIntercept 标志位,当disallowInterceptfalse时,调用onInterceptTouchEvent() 方法,并将返回值赋值给intercepted ,否则当disallowIntercepttrue时,则直接将intercepted 赋值为false

disallowIntercept 标记位可以通过公共方法 requestDisallowInterceptTouchEvent() 设置,通常由子View调用,当设置为true 后,ViewGroup 将无法拦截除ACTION_DOWN 之外的点击事件,原因是当事件为ACTION_DOWN 时,ViewGroup 会重置disallowIntercept 标记位,并且将mFirstTouchTarget 设置为null,因此,当事件为ACTION_DOWN 时,ViewGroup 总是会调用自己的onInterceptTouchEvent()方法。

        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // 如果是Down事件,则重置所有之前保存的状态,因为这是事件序列的开始
            // mFirstTouchTarget会被设为Null
            cancelAndClearTouchTargets(ev);
            // 重置FLAG_DISALLOW_INTERCEPT
            resetTouchState();
        }

        // 检测是否拦截
        final boolean intercepted;
        if (actionMasked == MotionEvent.ACTION_DOWN
                || mFirstTouchTarget != null) {
            // 标记事件不允许被拦截,默认为false
            // 可以由requestDisallowInterceptTouchEvent方法来设置
            // 设置为true,ViewGroup将无法拦截Down以外的点击事件
            final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
            if (!disallowIntercept) {
                // 调用onInterceptTouchEvent(ev)方法,询问自己是否要拦截事件
                // ViewGroup的onInterceptTouchEvent(ev)方法默认返回false
                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;
        }

事件分发

中间经过标记和action检查cancel,将结果赋值给变量canceledif (!canceled && !intercepted) 语句表明,事件未被取消且interceptedfalse(未拦截),则会进入执行语句中。

首先判断childrenCount不为0,然后通过buildTouchDispatchChildList()方法拿到子元素的List集合,接着倒序遍历所有子元素,寻找可以接收点击事件的子元素,为什么要倒序遍历,是因为buildTouchDispatchChildList()内部会调用buildOrderedChildList()方法,该方法会将子元素根据Z轴排序,在同一Z平面上的子元素则会根据绘制的先后顺序排序,触摸的时候我们当然会希望浮在最上层的元素最先响应事件。

对于每一个子元素来说,需要canViewReceivePointerEvents()isTransformedTouchPointInView()均返回true,才说明该子元素可以处理触摸事件,否则直接continue进行下一次循环。

canViewReceivePointerEvents()通过是否可见及是否在播放动画来判断子元素是否可以接收事件,isTransformedTouchPointInView()判断触摸事件的坐标点是否在子元素内,这样我们就获得了可以处理触摸事件的子元素。

接下来通过getTouchTarget()方法判断当前子元素是否已经赋值给mFirstTouchTarget,如果newTouchTarget不为null,说明子元素已经在mFirstTouchTarget中,执行break跳出循环。

如果newTouchTargetnull,说明子元素并没有在mFirstTouchTarget中保存,此时调用dispatchTransformedTouchEvent()方法,该方法十分重要,在该方法内部:如果子元素是ViewGroup并且事件没有被拦截,那么递归调用ViewGroupdispatchTouchEvent();如果子元素是View,那么调用ViewdispatchTouchEvent() ,最终会调用ViewonTouchEvent()

dispatchTransformedTouchEvent() 方法是有返回值的,如果返回true,说明子元素消耗了触摸事件,则在下面的代码中将子元素赋值给mFirstTouchEvent ,并跳出循环,mFirstTouchTarget是否被赋值,将直接影响到ViewGroup对事件的拦截策略,如果mFirstTouchTargetnull,那么ViewGroup就会默认拦截接下来同一序列中的所有触摸事件,这一点在后面分析;如果返回falseViewGroup就会把事件分发给下一个子元素(如果还有下一个子元素的话)。

            // 如果没取消也没拦截,进入方法体中
            if (!canceled && !intercepted) {
              
            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;
                // 判断newTouchTarget为Null,且ChildrenCount不为0
                if (newTouchTarget == null && childrenCount != 0) {
                    final float x = ev.getX(actionIndex);
                    final float y = ev.getY(actionIndex);
                    // 寻找可以接受触摸事件的子View
                    // 通过buildTouchDispatchChildList()方法构建子View的List集合preorderedList
                    final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                    final boolean customOrder = preorderedList == null
                            && isChildrenDrawingOrderEnabled();
                    final View[] children = mChildren;
                    // 倒序遍历所有的子View
                    for (int i = childrenCount - 1; i >= 0; i--) {
                        final int childIndex = getAndVerifyPreorderedIndex(
                                childrenCount, i, customOrder);
                        final View child = getAndVerifyPreorderedView(
                                preorderedList, children, 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;
                        }

                        // 同时满足两种情况下子View可以接收事件的分发
                        // canViewReceivePointerEvents()方法会判断子View是否可见和是否在播放动画
                        // isTransformedTouchPointInView()方法会判断触摸事件坐标是否在子View内
                        if (!canViewReceivePointerEvents(child)
                                || !isTransformedTouchPointInView(x, y, child, null)) {
                            ev.setTargetAccessibilityFocus(false);
                            continue;
                        }

                        // 查找当前子View是否在mFirstTouchTarget中存储
                        // 找不到则返回Null
                        newTouchTarget = getTouchTarget(child);
                        if (newTouchTarget != null) {
                            // newTouchTarget不为Nul,说明已经找到接收的View了,break跳出for循环
                            newTouchTarget.pointerIdBits |= idBitsToAssign;
                            break;
                        }
                      
                        resetCancelNextUpFlag(child);
                      
                        // 没有跳出循环,说明我们找到的Child并没有在mFirstTouchTarget中
                        // 调用dispatchTransformedTouchEvent()方法
                        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();
                            // 将child赋值给mFirstTouchTarget
                            newTouchTarget = addTouchTarget(child, idBitsToAssign);
                            // alreadyDispatchedToNewTouchTarget赋值为true,跳出循环
                            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();
                }

当没有任何子元素处理触摸事件时,调用dispatchTransformedTouchEvent() 方法,注意此时第三个参数传入null,在方法内部就会调用super.dispatchTouchEvent() ,也就是View类的dispatchTouchEvent()

if (mFirstTouchTarget == null) {
            // 如果mFirstTouchTarget为null
            // 调用dispatchTransformedTouchEvent()方法
            // 第三个参数为null,会调用super.dispatchTouchEvent()方法
            // 将当前ViewGroup当做普通的View处理
            handled = dispatchTransformedTouchEvent(ev, canceled, null,
                    TouchTarget.ALL_POINTER_IDS);

onInterceptTouchEvent() 方法

if语句判断触摸事件来源是否为鼠标或其他指针式设备,其他情况下默认返回false

public boolean onInterceptTouchEvent(MotionEvent ev) {
    if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
            && ev.getAction() == MotionEvent.ACTION_DOWN
            && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
            && isOnScrollbarThumb(ev.getX(), ev.getY())) {
        return true;
    }
    return false;
}

dispatchTransformedTouchEvent() 方法

dispatchTransformedTouchEvent() 源码中发现多次对于传入的child是否为null做判断,并且都做类似的操作:

child==null时,调用super.dispatchTouchEvent(),也就是View类的dispatchTouchEvent()方法,因为ViewGroup的父类是View,最终会调用ViewonTouchEvent()方法。

child!=null时,递归调用child.dispatchTouchEvent(),此时child可能是View,也可能是ViewGroup

从源码中可以看出dispatchTransformedTouchEvent() 方法的返回值,最终取决于onTouchEvent()方法,也就是说,onTouchEvent()是否消费了事件,决定了dispatchTransformedTouchEvent() 方法的返回值,从而决定mFirstTouchTarget是否为null 。因为如果dispatchTransformedTouchEvent() 方法的返回值为false,就无法执行addTouchTarget()方法,而mFirstTouchTarget就是在该方法中被赋值的。

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

重要结论

  1. ViewGroup一旦拦截ACTION_DOWN事件,那么当ACTION_MOVEACTION_UP事件到来时,将不再调用ViewGrouponInterceptTouchEvent()方法,并且同一序列中的其他事件都会默认交给它处理。

    分析:ViewGroup拦截ACTION_DOWN事件,会导致interceptedtrue,从而导致if (!canceled && !intercepted)判断不成立,跳过执行语句,mFirstTouchTarget也为null。那么当ACTION_MOVEACTION_UP事件到来时,if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null)判断语句不成立,会直接将intercepted赋值为true,即默认拦截后续的所有事件。

  2. 某个View一旦开始处理事件,如果它不消费ACTION_DOWN事件,那么同一事件序列中的其他事件也不会再交给它来处理,并且事件将重新交给它的父容器去处理。

    分析:某个View不消费ACTION_DOWN事件,即dispatchTransformedTouchEvent()方法返回了false,导致if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign))判断语句不成立,跳过执行语句,同样导致mFirstTouchTargetnull ,那么和第一条结论的分析一样,当ACTION_MOVEACTION_UP事件到来时,if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null)判断语句不成立,同样会直接将intercepted赋值为true ,所以后续的事件都无法传递到这个View,而是交给ViewGroup处理。

  3. ViewGroup(绝大多数情况下)默认不拦截任何事件。Android源码中ViewGrouponInterceptTouchEvent()方法默认返回false

  4. ViewGroup没有重写父类ViewonTouchEvent()方法。


  • 到这里就分析完了,查了很多资料,中间也有可能有理解错误的地方,如果哪里错了,还请大家指正,谢谢。
  • Github
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,607评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,047评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,496评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,405评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,400评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,479评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,883评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,535评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,743评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,544评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,612评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,309评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,881评论 3 306
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,891评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,136评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,783评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,316评论 2 342

推荐阅读更多精彩内容