从源码的角度了解事件分发机制

422 阅读6分钟

前言

Android开发中,事件分发已经成为开发者的必备知识,那么如果面试官让你讲一下对事件分发的理解,你将会怎么去讲呢?

我们都在说的事件分发的本质是什么呢?

我们都知道事件的传递和分发都是在手指触发屏幕的一瞬间开始,那么在触发后,系统会做出什么反应呢?

接下来,让我们一一揭开这层神秘的面纱。

事件的传递机制

所有的事件发生的起源就在于Touch事件,我们的在屏幕上的操作动作,可以分为四种:

动作 描述
MotionEvent.ACTION_DOWN 在页面上按下某个位置
MotionEvent.ACTION_MOVE 手指在页面上进行移动(滑动)
MotionEvent.ACTION_UP 手指抬起
MotionEvent.ACTION_CANCEL 结束事件(在ACTION_UP后会执行)

从用户角度来说,我们手指接触的地方是一个页面,也就是我们所说的UI,UI从上到下依次是ActivityViewGroupView

有可能一个ViewGroup里还有一个或者多个ViewGroup,这里我们只哪最简单的页面构造来分析。

那么显然得知,事件的传递机制就是从上到下的,依次就是 Activity -> ViewGroup -> View

事件的分发机制

事件的分发涉及到三个方法:

dispathTouchEvent

onInterceptTouchEvent

onTouchEvent

它们三者的调用关系可以用一个经典的例子来说明:

public boolean dispatchTouchEvent(MotionEvent ev) {
    boolean consume = false;
    if(onInterceptTouchEvent(ev)) {
        consume = onTouchEvent(ev)
    } else {
        consume = child.dispatchTouchEvent(ev)
    }
    return consume;
}

事件的传递首先从Activity开始,直到有一个控件处理了这个事件。我们来看下源码中做了些什么。

Activity的分发机制

    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

1、onUserInteraction是一个空方法。

2、由上边代码可以看出,Activity会发送给依附的Window来处理,如果Window中没有处理这个事件,就会交给Activity的onTouchEvent去处理。

那么这个getWindow是什么呢?

Window是一个抽象类,它的实现类是PhoneWindow

PhoneWindow
    @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);
    }
DecorView
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }

DecorView是Activity的顶层View,继承FrameLayout,也就是说Activity中的点击事件会传递到ViewGroup中,我们来看下ViewGroup中的分发机制,这也是本篇中比较难的点。

ViewGroup的分发机制

dispatchTouchEvent

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

这是dispatchTouchEvent中的一段逻辑,代码比较多我们一点点分析。

由上面代码我们可以看到ViewGroup的拦截首先要满足两个条件:actionMasked == MotionEvent.ACTION_DOWN以及mFirstTouchTarget != null,第一个很好理解,第二个是什么呢?这里我们留一个疑问,接着往下看。

disallowIntercope中的关键在FLAG_DISALLOW_INTERCEPT标志位,如果这个标志位被设置了,那么将不会被拦截。看下之前的一段代码:

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

如果是ACTION_DOWN的话,就会重置状态,包括FLAG_DISALLOW_INTERCEPT,所以设置了FLAG_DISALLOW_INTERCEPT将不会拦截除了ACTION_DOWN之外的事件。

接下来我们看下不拦截之后的处理逻辑:

                    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<View> 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 (!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);
                            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;

这段比较长,我们来找一些重要的逻辑看下,首先遍历所有的子View,判断它们是不是处理了这个事件。

判断的依据有三个:

                            if (childWithAccessibilityFocus != null) {
                                if (childWithAccessibilityFocus != child) {
                                    continue;
                                }
                                childWithAccessibilityFocus = null;
                                i = childrenCount - 1;
                            }

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

1、当前child是否可获得焦点。

2、当前child是否正在执行动画。

3、当前事件的坐标是否在child的区域内。

如果这些都满足,就会调用dispatchTransformedTouchEvent方法来将事件分发给child去处理。

dispatchTransformedTouchEvent

            if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else {
                handled = child.dispatchTouchEvent(event);
            }

如果有child处理了事件,则addTouchTarget,并跳出循环

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

看了addTouchTarget方法是不是就可以解答上面的疑问了?

mFirstTouchTarget是一个单链表,指向处理了事件的child,它的赋值与否直接影响了ViewGroup的拦截逻辑。

接着往下看:

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

如果所有的child都没有处理事件,那么就会走super.dispatchTouchEvent(event).

ViewGroup的super当然就是View了,看看,是不是最终会走到View的处理逻辑里。

View的分发机制

View的处理逻辑就相对来说,简单多了,我们来看下:

    public boolean dispatchTouchEvent(MotionEvent event) {
        ....

        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;
            }
        }
        ...
        return result;
    }

看上面的代码,我们发现它会先判断OnTouchListener,如果设置了OnTouchListener,就会走里面的onTouch方法,否则才会走onTouchEvent

我们来看下onTouchEvent方法:

      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 (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }

首先会判断是不是不可用状态,如果是不可用状态也是会消费事件的,其次的代理的判断。

           switch (action) {
                case MotionEvent.ACTION_UP:
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
                        handleTooltipUp();
                    }
                    if (!clickable) {
                        removeTapCallback();
                        removeLongPressCallback();
                        mInContextButtonPress = false;
                        mHasPerformedLongPress = false;
                        mIgnoreNextUpEvent = false;
                        break;
                    }
                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
                    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 (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                            focusTaken = requestFocus();
                        }

                        if (prepressed) {
                            // The button is being released before we actually
                            // showed it as pressed.  Make it show the pressed
                            // state now (before scheduling the click) to ensure
                            // the user sees it.
                            setPressed(true, x, y);
                        }

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

只要是点击状态是CLICKABLE或者LONG_CLICKABLE都会消费事件,最终会走到performClickInternal, performClickInternal中其实是调用的performClick

    public boolean performClick() {
        // We still need to call this method to handle the cases where performClick() was called
        // externally, instead of through performClickInternal()
        notifyAutofillManagerOnClick();

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

        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);

        notifyEnterOrExitForAutoFillIfNeeded(true);

        return result;
    }

在这个方法中会调用我们熟知的OnClickListener

    public void setOnClickListener(@Nullable OnClickListener l) {
        if (!isClickable()) {
            setClickable(true);
        }
        getListenerInfo().mOnClickListener = l;
    }

我们每个View的默认LONG_CLICKABLE都是false的,CLICKABLE大都也是false的,看上面代码可知,在 setOnClickListener会将CLICKABLE设置为true。

总结

到这里,事件分发的机制就了解完了,你是不是对刚开始提出的问题有了答案了呢?