Android事件分发全面解析,带你一起看源码

Android事件分发机制是Android高级工程师考核的标准之一,可以说是重中之重,掌握其原理我们可以轻松的解决一些特殊问题,例如滑动冲突。今天我们一起通过阅读源码,来剥开它的神秘面纱。
首先我们来看事件分发所涉及到的几个主要方法

  • public boolean dispatchTouchEvent(MotionEvent ev) :用来进行事件分发。如果事件能够传递给当前View,那么此方法一定会被调用,返回结果受当前View的onTouchEvent和下级View的dispatchTouchEvent方法的影响,表示是否消耗当前事件。
  • public boolean onInterceptTouchEvent(MotionEvent ev):ViewGroup中特有的方法,会在dispatchTouchEvent方法中调用,用来判断是否拦截某个事件,如果当前View拦截了某个事件,那么在同一个事件序列中,此方法不会再次被调用,返回结果表示是否拦截当前事件,并不决定是否消耗事件。
  • onTouchEvent();在dispatchTouchEvent方法中调用,用来处理点击事件,返回结果表示是否消耗当前事件,如果不消耗,则在同一个事件序列中,当前View无法再次接收到事件。
  • onTouchListener:如果设置了onTouchListener,onTouchListener的onTouch方法在dispatchTouchEvent方法中调用,其返回结果影响onTouchEvent是否被调用,并影响dispatchTouchEvent的返回结果,表示是否消耗当前事件.
  • onClickListener();onClickListener的onClick方法在onTouchEvent中,当点击事件为ACTION_UP时被调用。

我们现在了解了事件分发所设计的主要方法的含义之后,我们来一起通过源码来看一下一个的事件是怎么一步一步的进行传递的。我们知道当我们的点击操作发生时,事件冲Window开始,最先传递给我们的Activity,所以我们就先来从Actvity的dispatchTouchEvent方法开始分析。

    public boolean dispatchTouchEvent(MotionEvent ev) {    
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //如果是down事件的话,将会调用此方法,此方法提供给用户来进行重写,处理一些必要的逻辑。
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

我们可以看到它是调用getWindow().superDispatchTouchEvent()进行分发,如果为false表示事件没有被人消耗,将会调用Activity的onTouchEvent方法进行处理。getWindow返回的是Window对象,而Window只有唯一子类为PhoneWindow,也就是这里会调用PhoneWindow的superDispatchTouchEvent方法。

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

继续调用mDecor.superDispatchTouchEvent方法,而mDecor是DecorView。DecorView是我们Activity的根View,也是我们设置布局的根View,我们继续看DecorView是怎么做的。

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

调用的父类的dispatchTouchEvent,而它的父类为FrameLayout没有此方法,此方法在FrameLayout的父类ViewGroup中。

    public boolean dispatchTouchEvent(MotionEvent ev) {
...
        boolean handled = false;

            // Handle an initial down.
            if (actionMasked == MotionEvent.ACTION_DOWN) {
               //清除所有Targets
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }

            /**1、当Action为DOWN或者没有子View消费事件的时候,调用onInterceptTouchEvent方法来
             *判断是否要拦截事件,其中有个标记位FLAG_DISALLOW_INTERCEPT,意思是是否允许ViewGroup
             *拦截事件,如果不允许,ViewGroup将不会调用onIterceptTouchEvent
             *2、当我们不是Down事件的时候,并且我们没有子View去处理的时候,整个事件序列会默认全部被我们的
             *顶层View也就是DecorView拦截。DecorView默认并不消耗事件,所以最后还是返回给Activity的onTouchEvent去处理
             *3、对ViewGroup而言。拦截不一定消耗事件,但是不拦截一定消耗不了事件。
             */
            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;
            }
            ...
            //不是cancled事件,并且没有被拦截
            if (!canceled && !intercepted) {

                View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
                        ? findChildWithAccessibilityFocus() : null;

                if (actionMasked == MotionEvent.ACTION_DOWN
                        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                    final int actionIndex = ev.getActionIndex(); // always 0 for down
                    final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
                            : TouchTarget.ALL_POINTER_IDS;

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

                    final int childrenCount = mChildrenCount;
                    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;
                        //1.遍历所有子View,当子View没有在播放动画,并且子View在焦点之上的时候,将事件分发给子View
                        //2.当子View的消耗此事件,将mFirstTouchTarget进行赋值并把dispatchtouchEvent返回为true,表示消耗此事件
                        //3.当没有子View可以消耗此事件的话就,调用自己的onTouchEvent方法。如果没有
                        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 (!canViewReceivePointerEvents(child)
                                    || !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);
                            //真正的分发逻辑,分发给child,如果child消耗事件,设置给TouchTarget,之后的序列事件将会给这个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;
                    }
                }
            }

            // Dispatch to touch targets.
            //当没有子View处理事件,将调用dispatchTransformedTouchEvent方法进行分发,第三个参数为null。
            //内部super.dispatchTouchEvent(event);也就是调用我们的View的dispatchTouchEvent,也就是说我们
            //ViewGrop的事件分发如果没人处理或者自己拦截处理的话最终还是调用View的分发逻辑。
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
            //如果有子View处理Down事件,接下来的move和up事件将直接走这里的逻辑直接分发给我们的mFirstTouchTarget的View。
                // Dispatch to touch targets, excluding the new touch target if we already
                // dispatched to it.  Cancel touch targets if necessary.
                TouchTarget predecessor = null;
                TouchTarget target = mFirstTouchTarget;
                while (target != null) {
                    final TouchTarget next = target.next;
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            handled = true;
                        }
                        if (cancelChild) {
                            if (predecessor == null) {
                                mFirstTouchTarget = next;
                            } else {
                                predecessor.next = next;
                            }
                            target.recycle();
                            target = next;
                            continue;
                        }
                    }
                    predecessor = target;
                    target = next;
                }
            }

            // Update list of touch targets for pointer up or cancel, if needed.
            if (canceled
                    || actionMasked == MotionEvent.ACTION_UP
                    || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                resetTouchState();
            } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
                final int actionIndex = ev.getActionIndex();
                final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
                removePointersFromTouchTargets(idBitsToRemove);
            }
       
        return handled;
    }

总结:

  • 当Down事件发生时,首先ViewGroup的dispatchTouchEvent方法执行,这时,没有子mFirstTouchTarget=null也就是还没有子View处理事件
  • ViewGroup开始通过FLAG_DISALLOW_INTERCEPT标记位来判断是否允许ViewGroup拦截事件。如果允许拦截,调用onInterceptTouchEvent方法判断是否拦截。如果拦截,将不会有子View收到消息分发,直接调用super的dispatchTouchEvent方法。也就是走了View的事件分发流程。此流程下面会讲
  • 如果ViewGroup不拦截事件,将会遍历它是所有子View,找到能接受事件的View(在点击事件之上,并且没有在执行动画),进行分发,如果子View是ViewGroup重新走以上逻辑,如果子View是个View将调用子View的dispatchTouchEvent走View的分发逻辑,如果没有子View处理事件,将走ViewGroup的super.dispatchTouchEvent方法。如果子View或ViewGroup消耗了此事件,将这个View设置给View的mFistTouchTager变量,之后的一系列事件都将由这个View处理。
    从上面我们看到,如果ViewGroup拦截,或者没有子View去消耗事件,都將走View的分发逻辑,而如果子View是View的话也会走VIew的分发逻辑,我们来看一下View的dispatchTouchEvent方法
   public boolean dispatchTouchEvent(MotionEvent event) {
...
        boolean result = false;
...
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }
...
        return result;
    }

View的dispatchTouchEvent方法就比较简单返回结果是是否消耗此事件,如果设置了onTouchListener,会调用onTouch,如果返回了true将消耗这个事件,并且不会调用onTouchEvent方法。如果onTouch返回了false onTouchEvent才能被调用。

    public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();

        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                setPressed(false);
            }
            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
            return clickable;
        }

...
        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
                case MotionEvent.ACTION_UP:
             ...
                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
                        // take focus if we don't have it already and we should in
                        // touch mode.
                        boolean focusTaken = false;
                      
                    ...
                        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)) {
                                    performClick();
                                }
                            }
                        }

                        if (mUnsetPressedState == null) {
                            mUnsetPressedState = new UnsetPressedState();
                        }

                        if (prepressed) {
                            postDelayed(mUnsetPressedState,
                                    ViewConfiguration.getPressedStateDuration());
                        } else if (!post(mUnsetPressedState)) {
                            // If the post failed, unpress right now
                            mUnsetPressedState.run();
                        }

                        removeTapCallback();
                    }
                    mIgnoreNextUpEvent = false;
                    break;
            }
            return true;
        }
        return false;
    }

从View的onTouchEvent源码中可以看出,是否消费此事件是根据View的Clickable 和longClickable 决定的,如果它们两个中有一个为ture 那么不管 我们的 enable 是不是disable 都会消耗此事件。如果我们的enable为true。在up事件产生的时候会判断并调用performClick方法。这个的实现就是我们的onclick方法。也就是说我们onClick方法是事件分发的最尾端。
最后我们要知道,当我们的Down事件进行分发的时候,如果没有任何View进行消费的话,之后的一系列事件,我们的顶层DecorView会默认进行拦截,调用它的onTouchEvent,并且默认DecorView是不消耗的,最终会返回给我们的Actvity并调用他的onTouchEvent方法。
以上就是我们事件分发的整体流程。
参考资料:(十八)事件分发-源码分析
安卓开发艺术探索第三章View事件分发机制

你可能感兴趣的:(Android事件分发全面解析,带你一起看源码)