Android中ViewGroup的dispatchTouchEvent方法源码分析(二)

ps:本文系为转载文章,阅读原文可读性会更好,文章末尾有原文链接

ps:源码是基于 android api 27 来分析的

这一篇是继Android中ViewGroup的dispatchTouchEvent方法源码分析(一)来写的,首先我们先把 ViewGroup的dispatchTouchEvent 方法源码全部列出来;

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {

    //6、
    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);
    }

    //7、
    boolean handled = false;

    //8、
    if (onFilterTouchEventForSecurity(ev)) {
        final int action = ev.getAction();

        //9、
        final int actionMasked = action & MotionEvent.ACTION_MASK;

        //10、
        // 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();
        }

        //11、
        // Check for interception.
        final boolean intercepted;

        //12、
        if (actionMasked == MotionEvent.ACTION_DOWN
                || mFirstTouchTarget != null) {

            //13、
            final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
            if (!disallowIntercept) {

                //14、
                intercepted = onInterceptTouchEvent(ev);

                //15、
                ev.setAction(action); // restore action in case it was changed
            } else {
                intercepted = false;
            }

            //16、
        } 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);
        }

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

        //18、
        // Update list of touch targets for pointer down, if needed.
        final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;

        //19、
        TouchTarget newTouchTarget = null;

        //20、
        boolean alreadyDispatchedToNewTouchTarget = false;

        //21、
        if (!canceled && !intercepted) {

            //21、
            // 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) {

                //22、
                final int actionIndex = ev.getActionIndex(); // always 0 for down

                //23、
                final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
                        : TouchTarget.ALL_POINTER_IDS;

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

                final int childrenCount = mChildrenCount;

                //25、
                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 preorderedList = buildTouchDispatchChildList();

                    //26、
                    final boolean customOrder = preorderedList == null
                            && isChildrenDrawingOrderEnabled();

                    //27、
                    final View[] children = mChildren;
                    for (int i = childrenCount - 1; i >= 0; i--) {

                        //28、
                        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;
                        }

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

                        //30、
                        newTouchTarget = getTouchTarget(child);

                        //31、
                        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;
                        }

                        //32、
                        resetCancelNextUpFlag(child);

                        //33、
                        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();
                }

                //34、
                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;
                }
            }
        }

        //35、
        // Dispatch to touch targets.
        if (mFirstTouchTarget == null) {

            //36、
            // No touch targets so treat this as an ordinary view.
            handled = dispatchTransformedTouchEvent(ev, canceled, null,
                    TouchTarget.ALL_POINTER_IDS);

            //37、
        } else {

            //38、
            // 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 {

                    //39、
                    final boolean cancelChild = resetCancelNextUpFlag(target.child)
                            || intercepted;

                    //40、
                    if (dispatchTransformedTouchEvent(ev, cancelChild,
                            target.child, target.pointerIdBits)) {
                        handled = true;
                    }

                    //41、
                    if (cancelChild) {

                        //42、
                        if (predecessor == null) {
                            mFirstTouchTarget = next;

                            //43、
                        } else {
                            predecessor.next = next;
                        }
                        target.recycle();
                        target = next;
                        continue;
                    }
                }

                //44、
                predecessor = target;
                target = next;
            }
        }

        //45、
        // Update list of touch targets for pointer up or cancel, if needed.
        if (canceled
                || actionMasked == MotionEvent.ACTION_UP
                || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
            resetTouchState();

            //46、
        } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
            final int actionIndex = ev.getActionIndex();
            final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
            removePointersFromTouchTargets(idBitsToRemove);
        }
    }

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

我们接着Android中ViewGroup的dispatchTouchEvent方法源码分析(一)文章没有分析完的代码进行分析;

    //21、
    if (!canceled && !intercepted) {
            ......
            //25、
            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 preorderedList = buildTouchDispatchChildList();

                //26、
                final boolean customOrder = preorderedList == null
                        && isChildrenDrawingOrderEnabled();

                //27、
                final View[] children = mChildren;
                for (int i = childrenCount - 1; i >= 0; i--) {

                    //28、
                    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;
                    }

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

                    //30、
                    newTouchTarget = getTouchTarget(child);

                    //31、
                    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;
                    }

                    //32、
                    resetCancelNextUpFlag(child);

                    //33、
                    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();
            }
            ......
        }
    }

注释25 表示如果新的触摸对象为 null 并且当前 ViewGroup 有子元素;注释26 表示是否使用自定义的顺序来添加控件,可以理解为是否按照 draw 的顺序;注释27 表示 ViewGroup 的子元素数组;注释28 可以理解为如果是用了自定义的顺序来添加控件,那么绘制的 View 的顺序和 mChildren 的顺序是不一样的,因此根据 getChildDrawingOrder 方法取出真正的绘制的 View;注释29 表示如果 child 不可以接收这个触摸的事件,即 child 不是 visiable,或者是否没有动画,也就是判断 x, y 是否没有在 view 的区域内,这就是为什么补间动画的触发区域不随着动画而改变的原因了;注释30 表示查找 child 是否已经记录在 mFirstTouchTarget 这个单链表中;注释31 表示果新的触摸目标对象不为空,那么就把这个触摸的 id 赋予它;注释32 表示子 View 如果不在之前的触摸目标列表中,就会重置子 view 的标志;注释33 表示将相应的事件传递下去,不过 event 被传递给 child 的时候将会做相应偏移,假设子 View 接收并且处理了这个事件,那么就更新上一次触摸事件的信息,并且会创建一个新的触摸目标对象,给这个子 view 和 pointer 的 id 进行绑定。

    ......
    //21、
    if (!canceled && !intercepted) {
        ......
        if (actionMasked == MotionEvent.ACTION_DOWN
                || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
            ......
            //34、
            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;
            }
        }
    }
    ......

注释34 表示如果没有 child 响应该事件,则将此事件交给最近加入的 target。

   ......
    //35、
    // Dispatch to touch targets.
    if (mFirstTouchTarget == null) {

        //36、
        // No touch targets so treat this as an ordinary view.
        handled = dispatchTransformedTouchEvent(ev, canceled, null,
                TouchTarget.ALL_POINTER_IDS);

        //37、
    } else {

        //38、
        // 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;
            
            //38A、
            if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                handled = true;
            } else {

                //39、
                final boolean cancelChild = resetCancelNextUpFlag(target.child)
                        || intercepted;

                //40、
                if (dispatchTransformedTouchEvent(ev, cancelChild,
                        target.child, target.pointerIdBits)) {
                    handled = true;
                }

                //41、
                if (cancelChild) {

                    //42、
                    if (predecessor == null) {
                        mFirstTouchTarget = next;

                        //43、
                    } else {
                        predecessor.next = next;
                    }
                    target.recycle();
                    target = next;
                    continue;
                }
            }

            //44、
            predecessor = target;
            target = next;
        }
    }
    ......

注释35 表示如果没有能响应该事件的 child,那么就会调用当前 ViewGroup 的 onTouchEvent 方法;注释36 表示 child 响应该事件;注释38A 表示如果已经将这个事件交给 newTouchTarget 处理过了,就不重复处理了,也就是如果在Android中ViewGroup的dispatchTouchEvent方法源码分析(一)这篇文章注释33 所在的代码处理过了;注释39 表示是否让 child 取消处理事件,如果是,则会分发给 child 一个 ACTION_CANCEL 事件;注释40 表示进行事件的分发;注释41 表示如果当前的 child 得到的是一个ACTION_CANCEL 事件;注释42 表示如果当前是第一个 TouchTarget,那么就把头去掉(predecessor 是一个单链表);注释43 表示把下一个赋予父节点的上一个,这样就把当前节点给丢掉;注释44 表示如果没有删除这个节点,那么下一轮父节点就是当前节点。

        ......
        //45、
        // Update list of touch targets for pointer up or cancel, if needed.
        if (canceled
                || actionMasked == MotionEvent.ACTION_UP
                || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
            resetTouchState();

            //46、
        } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
            final int actionIndex = ev.getActionIndex();
            final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
            removePointersFromTouchTargets(idBitsToRemove);
        }
        ......

注释45 表示 如果遇到了取消事件、或是单点触摸条件下手指离开,那么就要更新触摸的状态;如果是多点触摸下的手指抬起事件,就会根据 idBitsToRemove 从 TouchTarget 中移除掉对应的触摸点。

ViewGroup 的 dispatchTouchEvent 方法的代码可以用下面的伪代码表示;

public boolean dispatchTouchEvent(MotionEvent event) {

        boolean isIntercept =false;
        if(onInterceptTouchEvent(event)){
            isIntercept=true;
        }
        if(!isIntercept){
            boolean consume= child.dispatchTouchEvent(event);
            if(!consume){
                mFirstTouchTarget = null;
            }else{
                mFirstTouchTarget = addTouchTarget(child, idBitsToAssign);
            }
        }else{
            mFirstTouchTarget = null;
        }
        if(mFirstTouchTarget!=null){
            return true;
        }else{
            return onTouchEvent(event);
        }
}

你可能感兴趣的:(Android中ViewGroup的dispatchTouchEvent方法源码分析(二))