事件分发机制

124 阅读7分钟

View中事件分发

public boolean dispatchTouchEvent(MotionEvent event) {
    // If the event should be handled by accessibility focus first.
    if (event.isTargetAccessibilityFocus()) {
        // We don't have focus or no virtual descendant has it, do not handle the event.
        if (!isAccessibilityFocusedViewOrHost()) {
            return false;
        }
        // We have focus and got the event, then use normal event dispatch.
        event.setTargetAccessibilityFocus(false);
    }
    //是否处理了事件
    boolean result = false;

    if (mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onTouchEvent(event, 0);
    }

    final int actionMasked = event.getActionMasked();
    if (actionMasked == MotionEvent.ACTION_DOWN) {
        // Defensive cleanup for new gesture
        //停止嵌套滑动
        stopNestedScroll();
    }

    if (onFilterTouchEventForSecurity(event)) {
        //如果可见并且在拖动滚动条,则返回true
        if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
            result = true;
        }
        //noinspection SimplifiableIfStatement
        ListenerInfo li = mListenerInfo;
        //1.如果设置了OnTouchListener,则调用其onTouch方法,若返回true则dispatchTouchEvent也返回true
        if (li != null && li.mOnTouchListener != null
                && (mViewFlags & ENABLED_MASK) == ENABLED
                && li.mOnTouchListener.onTouch(this, event)) {
            result = true;
        }
        //2.调用onTouchEvent()方法
        if (!result && onTouchEvent(event)) {
            result = true;
        }
    }

    if (!result && mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
    }

    // Clean up after nested scrolls if this is the end of a gesture;
    // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
    // of the gesture.
    if (actionMasked == MotionEvent.ACTION_UP ||
            actionMasked == MotionEvent.ACTION_CANCEL ||
            (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
        stopNestedScroll();
    }

    return result;
}

View中的触摸事件要么交给开发者自己处理,要么使用默认处理。

如果开发者想自己来处理触摸事件,可通过setOnTouchListener(OnTouchListener),在OnTouchListener的onTouch()方法中实现自己的处理逻辑,且onTouch()需要返回true。

默认会调用View的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.
        //如果clickable但是View为disabled,那么也会消费事件只是不响应事件
        return clickable;
    }
    //如果设置了触摸代理则交由其处理事件
    if (mTouchDelegate != null) {
        if (mTouchDelegate.onTouchEvent(event)) {
            return true;
        }
    }
    //如果可点击或长按,则消费事件
    if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
        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)) {
                                //执行点击事件
                                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;

            case MotionEvent.ACTION_DOWN:
                if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
                    mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
                }
                mHasPerformedLongPress = false;

                if (!clickable) {
                    checkForLongClick(0, x, y);
                    break;
                }

                if (performButtonActionOnTouchDown(event)) {
                    break;
                }

                // Walk up the hierarchy to determine if we're inside a scrolling container.
                boolean isInScrollingContainer = isInScrollingContainer();

                // For views inside a scrolling container, delay the pressed feedback for
                // a short period in case this is a scroll.
                if (isInScrollingContainer) {
                    mPrivateFlags |= PFLAG_PREPRESSED;
                    if (mPendingCheckForTap == null) {
                        mPendingCheckForTap = new CheckForTap();
                    }
                    mPendingCheckForTap.x = event.getX();
                    mPendingCheckForTap.y = event.getY();
                    postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
                } else {
                    // Not inside a scrolling container, so show the feedback right away
                    //设置可点击标志位
                    setPressed(true, x, y);
                    //发送一个延迟消息,用于执行长按事件
                    checkForLongClick(0, x, y);
                }
                break;

            case MotionEvent.ACTION_CANCEL:
                if (clickable) {
                    setPressed(false);
                }
                removeTapCallback();
                removeLongPressCallback();
                mInContextButtonPress = false;
                mHasPerformedLongPress = false;
                mIgnoreNextUpEvent = false;
                mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                break;

            case MotionEvent.ACTION_MOVE:
                if (clickable) {
                    drawableHotspotChanged(x, y);
                }

                // Be lenient about moving outside of buttons
                //如果不在View区域内,则不响应点击、长按事件
                if (!pointInView(x, y, mTouchSlop)) {
                    // Outside button
                    // Remove any future long press/tap checks
                    removeTapCallback();
                    removeLongPressCallback();
                    if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                        setPressed(false);
                    }
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                }
                break;
        }

        return true;
    }

    return false;
}
  1. 检查是否可点击:View是否设置了点击(setOnClickListener())或长按事件(setOnLongClickListener())

  2. 当View为disabled状态时(setEnabled(false)),若View设置了点击或长按事件,那么View也会消费此次触摸事件,但是不会响应点击或长按事件。

  3. 如果设置了触摸代理(TouchDelegate),则交给代理处理触摸事件

  4. 触发点击事件
    在ACTION_DOWN时setPressed(true, x, y);设置点击标志位
    在ACTION_MOVE时如果触摸点超出了View区域setPressed(false);将移除点击标志
    在ACTION_UP时如果没有执行长按事件,则调用performClick()执行点击事件

  5. 触发长按事件
    在ACTION_DOWN时,checkForLongClick()会通过handle发送一个延迟消息处理长按事件
    在ACTION_MOVE时如果触摸点超出了View区域removeLongPressCallback();将移除长按消息
    在ACTION_UP时如果还没有执行长按事件将移除长按消息

ViewGroup中事件分发

ViewGroup事件分发分为3个部分:
1.是否拦截触摸事件
2.寻找合适的子View处理触摸事件
3.处理触摸事件

//检查是否拦截事件
final boolean intercepted;
//如果为ACTION_DOWN事件或者已有处理事件的对象
if (actionMasked == MotionEvent.ACTION_DOWN
        || mFirstTouchTarget != null) {
    //是否不允许拦截事件
    //子View调用requestDisallowInterceptTouchEvent(true)进行设置
    final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
    if (!disallowIntercept) {
        //如果允许拦截事件,则调用onInterceptTouchEvent方法决定是否拦截事件
        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;
}

子View可通过调用父View的requestDisallowInterceptTouchEvent(true)要求父View不对触摸事件进行拦截,交由子View处理。如果没有子View要求处理触摸事件,则会调用自身onInterceptTouchEvent()方法来决定是否拦截触摸事件,该方法默认不拦截。若拦截事件则自身处理触摸事件,若不拦截则交由子View处理。

//如果非取消事件并且不拦截事件,则在ACTION_DOWN时确定TouchTarget
if (!canceled && !intercepted) {

    // 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;
    //如果是ACTION_DOWN事件,找到合适的TouchTarget进行事件处理
    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;
        //如果newTouchTarget为null
        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.
            //获取排序后的子View列表
            final ArrayList<View> preorderedList = buildTouchDispatchChildList();
            final boolean customOrder = preorderedList == null
                    && isChildrenDrawingOrderEnabled();
            final View[] children = mChildren;
            //遍历所有子View
            for (int i = childrenCount - 1; i >= 0; i--) {
                //child索引位置
                final int childIndex = getAndVerifyPreorderedIndex(
                        childrenCount, i, customOrder);
                //获取子View
                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不可见并且没有设置动画并且触摸点没有落在子View上,则继续遍历下一个子View
                if (!canViewReceivePointerEvents(child)
                        || !isTransformedTouchPointInView(x, y, child, null)) {
                    ev.setTargetAccessibilityFocus(false);
                    continue;
                }
                //当子View可见或者设置了动画,并且触摸点位于子View上时
                //由于mFirstTouchTarget为null,所以下面代码不会执行
                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);
                //交由子View处理事件
                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 {
                        //保存最后触摸View的索引
                        mLastTouchDownIndex = childIndex;
                    }
                    //保存最后触摸的位置
                    mLastTouchDownX = ev.getX();
                    mLastTouchDownY = ev.getY();
                    //mFirstTouchTarget为当前处理事件的View
                    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;
        }
    }
}

当ViewGroup不拦截事件时,就需要去寻找一个合适的子View来处理触摸事件,只有在触摸事件开始时(ACTION_DOWN)才会去寻找。
遍历ViewGroup的所有子View,当子View可见或者设置了动画,并且触摸点位于子View上时。尝试使用该子View来处理触摸事件,调用其dispatchTouchEvent()方法。

// Dispatch to touch targets.
//开始分发事件
if (mFirstTouchTarget == null) {
    // No touch targets so treat this as an ordinary view.
    //如果没有找到合适的TouchTarget则交由自身处理
    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则交由其处理
    TouchTarget predecessor = null;
    TouchTarget target = mFirstTouchTarget;
    while (target != null) {
        final TouchTarget next = target.next;
        //如果TouchTarget已经处理了(在ACTION_DOWN时)就不再处理
        if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
            handled = true;
        } else {
            //是否TouchTarget取消事件或拦截事件
            final boolean cancelChild = resetCancelNextUpFlag(target.child)
                    || intercepted;
            //TouchTarget开始处理事件
            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;
    }
}

当没有找到合适的子View处理触摸事件或子View没有消费触摸事件时,那么父View会自行处理dispatchTransformedTouchEvent(ev, canceled, null, TouchTarget.ALL_POINTER_IDS)将调用View中的dispatchTouchEvent()方法进行处理。
当找到了合适的子View时,调用dispatchTransformedTouchEvent(ev, cancelChild, target.child, target.pointerIdBits)交给子View处理,该方法又会调用子View的dispatchTouchEvent(),如果子View没有消费触摸事件则又会交由父View进行处理。

一句话概括就是:优先子View处理,如果子View处理不了则自己来处理。