Android事件分发机制

先说一些结论吧:

1、只有ViewGroup有onInterceptTouchEvent方法,但并不是每个触摸事件都走该方法,只有ACTION_DOWN事件以及ACTION_DOWN事件分发后,在该ViewGroup内找到能消费事件的子view,后续事件才会走该方法判断。同时它又会受disallowIntercept 影响,当子view调用了parent.requestDisallowInterceptTouchEvent方法后,该ViewGroup同样不会走onInterceptTouchEvent方法。
2、一般自定义ViewGroup会重写onInterceptTouchEvent,返回true,代表自身能消费事件,不再继续下发,走自己的onTouchEvent消费事件;返回false,代表不拦截事件,分发给子view处理。
3、一般自定义View还会重写onTouchEvent,该方法中通常会处理触摸的四种事件(不考虑多指)ACTION_DOWN、ACTION_MOVE、ACTION_UP、ACTION_CANCEL。当手指按在ViewGroup上时,事件就会从最外层或者说最顶层的ViewGroup依次向它们子View分发。而这一系列View中到底哪个能消费触摸事件是在ACTION_DOWN向下分发的过程中确立的!当ACTION_DOWN事件分发到View的onTouchEvent中时:
返回false,代表自己处理不了,让父View继续处理,后续事件走父View的onTouchEvent;
返回true,代表报告父View自己能够消费事件(将自身赋给父View的mFirstTouchTarget变量,具体看下方源码),后续事件看到这个mFirstTouchTarget,就都让它处理,这种情况下父View的onTouchEvent中无法接收ACTION_DOWN事件,但也有例外,如果后续事件如ACTION_MOVE,父View在OniterceptTouchEvnet中拦截了,那么,后续事件依然会给父View的onTouchEvent处理。
4、dispatchTouchEvent方法中处理了事件的分发逻辑,每种事件到底是拦截还是分发,亦或是处理,都和它息息相关。
它的返回值是给它的父View看的,return true,代表向父View报告自己能够消费事件;return false,让父View处理事件,然后父View会走自己的super.dispatchTouchEvent->onTouchEvent...;这一过程和onTouchEvent有点类似,都是在ACTION_DOWN事件分发中判定的。
5、一般自定义ViewGroup不建议重写dispatchTouchEvent方法,因为无论我们直接return true或false, 该ViewGroup的onTouchEvent就被屏蔽了,当然我们可以主动调用onTouchEvent,或super.dispatchTouchEvent执行向子view分发事件的逻辑,但这样有点复杂了,得不偿失。
6、对于mFirstTouchTarget和newTouchTarget未能理解透彻,暂时只是自己猜想(处理多指触控),如果哪位老铁知道的话,还望指点一下。

ViewGroup的dispatchTouchEvent,很重要!

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        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);
        }

        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            // 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.
                //当事件按下的时候,会先清除mFirstTouchTarget.
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }

            // Check for interception.
            final boolean intercepted;
            //down事件或上一次down事件中找到了消费触摸事件的子View,后续的事件都会判断一下子view是否要求不拦截
            //换句话说,也就是如果down事件没找到子View,那么后续事件就不会执行onInterceptTouchEvent();
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    //正常情况下会调用这个方法, 即是否拦截down事件, 该方法默认返回false.
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    //子View调用了requestDisallowInterceptTouchEvent(true),屏蔽onInterceptTouchEvent(ev)判断,直接不拦截事件。
                    intercepted = false;
                }
            } else {
                // There are no touch targets and this action is not an initial down
                // so this view group continues to intercept touches.
                //执行到这的时候代表此次事件为move或up, 且mFirstTouchTarget为空,即没有找到能消耗次事件的子View,所以直接拦截。
                intercepted = true;
            }

            // If intercepted, start normal event dispatch. Also if there is already
            // a view that is handling the gesture, do normal event dispatch.
            //如果拦截了,或者有找到了能消耗此次事件的子View。
            if (intercepted || mFirstTouchTarget != null) {
                ev.setTargetAccessibilityFocus(false);
            }

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

            // Update list of touch targets for pointer down, if needed.
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
            //newTouchTarget在此处声明
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
            //默认情况下, if能执行.
            //如果没有取消触摸,并且没有拦截事件。
            if (!canceled && !intercepted) {
                //我们将事件分发给能获取焦点的view,如果该view不处理该事件,那么我们就继续向该view的子view分发。
                // 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;
                //down事件进入判断
                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;
                    //假设次ViewGroup中有一个view, 则能进入if.(down)
                    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循环, 假设该viewGroup为relativelayout, 则会拿到最顶上的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
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }

                            //从touchTarget链表中寻找该child相关的target。第一次down是找不到的
                            **newTouchTarget = getTouchTarget(child);**
                            if (newTouchTarget != null) {
                                //多指触控,找到了target。
                                // 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);
                            //类似递归调用dispatchTransformedTouchEvent, 向子view分发事件, 只要没被拦截,该事件一直分发,返回子view 是否有能力消费触摸事件。
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                //找到了最终子view,且该子view能消费down事件
                                // 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 {
                                    //记录子view index
                                    mLastTouchDownIndex = childIndex;
                                }
                                mLastTouchDownX = ev.getX();
                                mLastTouchDownY = ev.getY();
                                //该child能消费触摸事件,生成newTouchTarget,同时赋给mFirstTouchTarget。
                                **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();
                    }
                    //处理多指触控,如第二根手指点击了子view范围之外,newTouchTarget无法找到,将第一根手指按下时的touchTarget给它。
                    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;
                    }
                }
            }

            // Dispatch to touch targets. 上述代码只是处理的down事件,后续事件将交给touchTarget处理。
            if (mFirstTouchTarget == null) {
                //如果down事件中未找到mFirstTouchTarget (没有消费事件的子view或onInterceptTouchEvent返回true),或者找到了mFirstTouchTarget,但后续的某一事件被它前置事件
                //所拦截,mFirstTouchTarget 重新被置空。 则此次事件走的是自身的(super)dispatchTouchEvent->onTouchEvent
                //这里体现了类似于向上递归分发处理事件的过程(即有些文章提到的事件分发过程是一个U形,从上往下,在从下往上,这里体现了从下往上的过程),上面处理ACTION_DOWN逻辑中调用子view的dispatchTouchEvent            
                //但没找到mFirstTouchTarget,那么就调用自己的super.dispatchTouchEvent。
                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) {
                    //遍历target链表
                    final TouchTarget next = target.next;
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        //down事件中找到了mFirstTouchTarget,且mFirstTouchTarget == newTouchTarget,多指触控
                        handled = true;
                    } else {
                        //是否被前置事件拦截
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        //move事件分发处理。
                        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;
    }

cancelAndClearTouchTargets

    /**
     * Cancels and clears all touch targets.
     */
    private void cancelAndClearTouchTargets(MotionEvent event) {
        if (mFirstTouchTarget != null) {
            boolean syntheticEvent = false;
            if (event == null) {
                final long now = SystemClock.uptimeMillis();
                event = MotionEvent.obtain(now, now,
                        MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
                event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
                syntheticEvent = true;
            }
            //清除mFirstTouchTarget
            for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
                resetCancelNextUpFlag(target.child);
                dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits);
            }
            //关注这句话.
            clearTouchTargets();

            if (syntheticEvent) {
                event.recycle();
            }
        }
    }

clearTouchTargets
每次down事件会清除target

    /**
    * Clears all touch targets.
    */
    private void clearTouchTargets() {
        TouchTarget target = mFirstTouchTarget;
        if (target != null) {
            do {
                TouchTarget next = target.next;
                target.recycle();
                target = next;
            } while (target != null);
            //这句话是核心,清除target
            mFirstTouchTarget = null;
        }
    }

dispatchTransformedTouchEvent
将viewGroup接收到事件的坐标,转化为在坐标在子view坐标体系中的坐标,如果参数child为空,则调用该ViewGroup父类中的dispatchTouchEvent->onTouch->onTouchEvent->onClickListener. 如果子view不为空, 则调用子view的dispatchTouchEvent,这是一个递归向下调用dispatchTouchEvent的过程

    /**
    * Transforms a motion event into the coordinate space of a particular child view,
    * filters out irrelevant pointer ids, and overrides its action if necessary.
    * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
    */
    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();
        //分发cancel事件
        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;
    }

参考:
https://www.jianshu.com/p/e99b5e8bd67b
http://blog.csdn.net/yanbober/article/details/45912661
https://www.jianshu.com/p/e75dd6fba1b7

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