ps:本文系为转载文章,浏览原文可读性会更好,文章开端有原文链接

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

这一篇是继Android中ViewGroup的dispatchTouchEvent办法源码剖析(一)来写的,首先咱们先把 ViewGroup的dispatchTouchEvent 办法源码全部列进去;

@Overridepublic 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<View> 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<View> 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);        }}