Android事件分发

MotionEvent

image.png

事件分发

事件分发基本流程

image.png

ViewGroup:先走分发流程,如果没有人处理接盘,则再走处理流程
View:只能走处理流程

分发流程

down 确定事件传给谁

  1. 先看是否拦截后自己处理(即不分发下去)
  2. 分发下去:
    排序
    遍历分发
    领取事件的View 处理事件
  3. 没人领取,再看下自己是否处理事件

move--处理事件
1.先看是否拦截后自己处理(即不分发下去)
2.分发下去:直接由down事件确定的view处理

  • 子view可以请求不拦截

事件冲突:事件只有一个,但有多个控件想要处理--最后处理这个事件的对象,不是我们想要给的对象,那么,也就是发生了事件冲突。

首先查看view的处理流程源码

        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }

            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }

当我们的事件是一个安全的,如果是正常的,则会进入到里面(正常流程肯定是正常的)。
看这里的判断条件

li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)

这种&& 是短路与,也就是,前面条件不符合,则后续也不会接着判断,所以,想要走到ontouch,则前面条件需要符合。
而li的赋值,代码中是赋值为mListenerInfo,而他的赋值,当我们设置setOnTouchListener后,就会对其进行初始化,而且如果设置了这个监听,那么必然也就不为null

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

 ListenerInfo getListenerInfo() {
        if (mListenerInfo != null) {
            return mListenerInfo;
        }
        mListenerInfo = new ListenerInfo();
        return mListenerInfo;
    }

并且由于button的ENABLED,默认就是开启的,所以,第三个条件也为true,而且,此时如果我们设置了setOnTouchListener且实现了ontouch方法,如果,我们ontouch方法返回为ture,则会命中这个if语句,如果返回为false,则不会进入这个if语句内部。即,我们如果使ontouch方法返回为ture,则会让result这个量赋值为true。

 if (!result && onTouchEvent(event)) {
                result = true;
            }

如果result赋值为true,则,这个if的短路与,就不回执行到onTouchEvent(event)。
所以这也就是为什么我们设置了setOnTouchListener且实现了ontouch方法返回为true,则会截断onTouchEvent(event)的调用。
另外由于onclicklistener是在onTouchEvent中进行的赋值,如果设置了setOnTouchListener且实现了ontouch方法返回为true,也同样会导致onclick设置后无效。

  if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                            // This is a tap, so remove the longpress check
                            removeLongPressCallback();

                            // Only perform take click actions if we were in the pressed state
                            if (!focusTaken) {
                                // Use a Runnable and post this rather than calling
                                // performClick directly. This lets other visual state
                                // of the view update before click actions start.
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                if (!post(mPerformClick)) {
                                    performClickInternal();
                                }
                            }
                        }

 performClickInternal();

 private boolean performClickInternal() {
        // Must notify autofill manager before performing the click actions to avoid scenarios where
        // the app has a click listener that changes the state of views the autofill service might
        // be interested on.
        notifyAutofillManagerOnClick();

        return performClick();
    }


performClick();

    final boolean result;
        final ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnClickListener != null) {
            playSoundEffect(SoundEffectConstants.CLICK);
            li.mOnClickListener.onClick(this);
            result = true;
        } else {
            result = false;
        }

紧接着看ViewGroup的分发流程

假使,从down事件开始看

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

可以看到,down事件的时候,会把我们之前的一些状态进行清除,所以,我们的一系列事件的起始,必然是down事件开始的。

  // Check for interception.
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    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语句,用到了||,所以,当我们第一个条件成立的时候,就会直接命中进入。
进入后,会判断事件是否会拦截

 final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    intercepted = false;
                }

假如,此时是拦截的,那么就会进入

  // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                // 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) {
                    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;
                }
            }

并且因为初次时,会在down中重置,那么此时mFirstTouchTarget==null
就会进入

 handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);

进入dispatchTransformedTouchEvent方法,因为第三个参数child为null
// 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);
        }

最终就会走到super.dispatchTouchEvent(transformedEvent);此处的super即view,即会走入view的dispatchTouchEvent的方法中,也就是上面看到的流程中。然后就会将他的返回值赋值给handled参数,最后return。也就将这个返回值传递给了ViewGroup类的dispatchTouchEvent方法中的handled参数最终返回。

假如,此时是不拦截的,那么后续流程就会走到这里

            if (!canceled && !intercepted) {

                // If the event is targeting accessibility 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) {
                    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 ArrayList preorderedList = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        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;
                            }

                            if (!child.canReceivePointerEvents()
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }

                            newTouchTarget = getTouchTarget(child);
                            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;
                            }

                            resetCancelNextUpFlag(child);
                            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();
                    }

                    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,
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE)
所以,就和我们之前记住的一个结论有了呼应----只有当down事件时,才会开始分发,如果你没拿到down事件,那么后续也就拿不到move up等事件。
但是这条结论有个前提,也就是,这个发生在view中而不是viewgroup中。因为在viewgroup中,如果你不处理down事件,也是可以处理后续的move等的。

现在分析的还是down事件,所以,进入这个if中接着看

   final ArrayList preorderedList = buildTouchDispatchChildList();

ArrayList buildOrderedChildList() {
        final int childrenCount = mChildrenCount;
        if (childrenCount <= 1 || !hasChildWithZ()) return null;

        if (mPreSortedChildren == null) {
            mPreSortedChildren = new ArrayList<>(childrenCount);
        } else {
            // callers should clear, so clear shouldn't be necessary, but for safety...
            mPreSortedChildren.clear();
            mPreSortedChildren.ensureCapacity(childrenCount);
        }

        final boolean customOrder = isChildrenDrawingOrderEnabled();
        for (int i = 0; i < childrenCount; i++) {
            // add next child (in child order) to end of list
            final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder);
            final View nextChild = mChildren[childIndex];
            final float currentZ = nextChild.getZ();

            // insert ahead of any Views with greater Z
            int insertIndex = i;
            while (insertIndex > 0 && mPreSortedChildren.get(insertIndex - 1).getZ() > currentZ) {
                insertIndex--;
            }
            mPreSortedChildren.add(insertIndex, nextChild);
        }
        return mPreSortedChildren;
    }

首先,这句话就是对子view对排列,内部代码为上述。
这里排列用到了getZ()。但是一般情况下,我们也不会写这个属性。所以,默认不写z进行排列的话,排序是把第一个view写到最后一个位置---因为后续是通过倒序取出的。
当我们把list返回回来后,紧接着就开始一个倒序当for循环取出

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

                            if (!child.canReceivePointerEvents()
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }

                            newTouchTarget = getTouchTarget(child);
                            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;
                            }

                            resetCancelNextUpFlag(child);
                            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);
                        }

取出第一个child之后,按照流程,会先对这个child进行一个判断,判断

if (!child.canReceivePointerEvents()
        || !isTransformedTouchPointInView(x, y, child, null)) {
         ev.setTargetAccessibilityFocus(false);
         continue;
       }

判断当前view是否可以接受事件(两个条件,一个是visibile,另一个是animation后,原有位置是否有因动画看不到了)。
还有就是判断这个事件是否在view范围内。
如果条件不满足,则会接着continue,进行下一步for当循环遍历
然后接着到一个很关键到方法内

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

dispatchTransformedTouchEvent这个方法,和之前看到有些区别,就在于第三个参数child,刚刚分析拦截时,这个参数为null,所以进入后,相应到判断逻辑肯定就会走到else中。

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

所以此时就会走 handled = child.dispatchTouchEvent(transformedEvent);调用到是这个child的dispatchTouchEvent方法。此时就得看这个child具体是谁了,如果是viewgroup,则相当于了递归遍历,再走一遍这个流程,如果是view,则到了最后处理到过程了。然后根据这个返回值进行刚才这个if语句到判断,如果是false,则代表到是,分发给了child,但是child可以选择是否进行消费
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign))
如果内部为true,则表示消费,命中了if,如果是false,则无法进入if语句到内部。
当返回为flase时,那么就会接着for循环当下一步遍历。
如果所有的for内部child都选择不处理,都返回false,则后续流程,就相当于了直接拦截的流程,走入到了

 // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            }

如果返回为true,命中了if,则会进入其中

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

这里有个最重要的地方, newTouchTarget = addTouchTarget(child, idBitsToAssign);

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

这里会对mFirstTouchTarget进行赋值,也就是到了这一步,mFirstTouchTarget终于有值了,不再是null。
此时,newTouchTarget==mFirstTouchTarget
target.next==null
并且还有一个变量alreadyDispatchedToNewTouchTarget = true;
然后就会break,结束了外层的for循环。
这就相当于,父布局问三个子布局,你们想要接受这个事件,当第一个孩子回答他要接受后,父布局也就不会在接着问第二个孩子和第三个孩子了。
此时接着往后走,因为mFirstTouchTarget!=null了,所以走到了else中

 // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                // 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) {
                    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;
                }
            }

然后在这个while中,肯定就会执行一次,因为我们只添加了一个(多点触摸会执行多次)
然后这个循环中, if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget)这个判断因为条件满足,就会直接将handled赋值为true。因为子child已经响应事件了,所以不会再处理事件了。

接着看MOVE事件

在down事件之后,我们也就知道要由谁处理这个事件了。
但是,move事件的走向,还是会先从最外层的父viewgroup开始走dispatch,由于是move事件,所以跟down事件所走的代码就不同了,因为判断条件肯定有的满足有的不满足了。

 final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    intercepted = false;
                }
            }

还会走到这个if内,虽然不是ACTION_DOWN,但是mFirstTouchTarget != null了,所以这个if还是命中了。
紧接着走到后续逻辑,由于之前没有拦截,则走到这个if中

 if (!canceled && !intercepted) {
    }

但是它不会再走到这个方法内

if (actionMasked == MotionEvent.ACTION_DOWN
                        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                        || actionMasked == MotionEvent.ACTION_HOVER_MOVE)

这个方法的作用,在down流程的分析中能看出,它是做分发事件用的。
所以move不会再分发事件了。
紧接着继续走到下面

 // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
                 }

但是由于mFirstTouchTarget != null,所以走到了else中
在else中的while里

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

if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget)这个if由于条件不在满足(alreadyDispatchedToNewTouchTarget这个量被重新赋值为false了),所以走到了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;
                        }

这里cancelChild为false,先记着,后续在看,涉及到另一个事件
然后在 if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits))分发给了target.child,也就是down事件中定了的谁处理事件。然后就走到了还是很熟悉的代码块中。
并且在这一步中,它走到了 child.dispatchTouchEvent

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是viewgroup,则又开始递归重走一遍重复流程,如果是view,则就开始处理这个事件了。所以MOVE事件正常流程也走完了。

看MOVE事件的拦截流程(事件冲突,只能在MOVE事件中处理)

这里就会分内部拦截发和外部拦截法。

  • 内部拦截法:子view处理事件冲突
  • 外部拦截法:父容器处理冲突

因为我们所有的事件,都会先走入这里

 final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    intercepted = false;
                }

先把这行代码写这里,这个很有用,很重要!
然后,以内部拦截法来说明,在内部拦截法的时候,有一个方法很重要,也就是requestDisallowInterceptTouchEvent,子view通过调用这个方法,可以修改disallowIntercept的值,也就能影响这个if进入的代码。
不过得注意down事件的时候,因为down事件在进入后,会把所有状态都重置,所以此时FLAG_DISALLOW_INTERCEPT肯定被重置了,那么disallowIntercept也就为fasle,也就命中了if

假设,我们在子view的move事件中调用requestDisallowInterceptTouchEvent(false)
那么move也就走入了if中。如果此时父view在拦截方法中返回为false,那么也就走入了拦截流程中。
但是此时有一个量变了,也就是

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

因为intercepted为true,也就导致了cancelChild改变,然后在dispatchTransformedTouchEvent方法中

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

此时cancel为true,也就进入了这里面(之前为false,所以也没看这块流程)
然后由于child!=null,所以就调用了handled = child.dispatchTouchEvent(event);这也就是为什么,父view拦截走,子view会走ACTION_CANCEL这个事件。
然后在后续代码中,因为cancelChild=ture
所以mFirstTouchTarget = next;
mFirstTouchTarget被赋值为了null。然后再下一个MOVE事件的时候,因为mFirstTouchTarget==null,所以直接导致走到了intercepted = true;的流程中。

所以以一个viewpaper嵌套recyclerview的例子中,如果采用内部拦截法解决滑动冲突,那么第一个move事件的目的,就是为了取消recyclerview事件(cancel事件)且mFirstTouchTarget被赋值为了null。所以,这个时候viewpaper是没有处理事件的。
当第二个move事件到来,他就走了到拦截流程中的if中

// Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            }else{
                }

也就和我们down事件的拦截的处理流程走的一样了,所以也就抢过来了事件。后续也就不会给view了,直接自己处理。
所以我们之前记得一个结论。
如果down事件不处理,则move事件也没法处理,是有前置条件的,它说的是view的,而viewgroup是可以抢过来move事件的。

所以,使用内部拦截法处理viewpaper +recyclerview的情况,当竖直滑动的时候,还可以水平滑动,但是当水平滑动的时候,却不能再竖直滑动了。

所以,也就是子view一旦拿到了事件,那么后续是由自己处理还是调用requestDisallowInterceptTouchEvent还给父布局,也就看自己怎么处理了。

你可能感兴趣的:(Android事件分发)