Android事件分发机制

源码基于 API 30

Android事件分发机制

Activity 事件分发

流程图:

Activity事件分发流程图

Activity#dispatchTouchEvent()

public boolean dispatchTouchEvent(MotionEvent ev) {
    // 一般事件都是从DOWN事件开始,故此处为true
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        onUserInteraction();
    }
    if (getWindow().superDispatchTouchEvent(ev)) {
        return true;
    }
    return onTouchEvent(ev);
}

Activity#onUserInteraction()

默认实现为空

当activity在栈顶时,按home,back,menu键时会触发此方法

public void onUserInteraction() {
}

PhoneWindow#superDispatchTouchEvent()

Activity#dispatchTouchEvent中调用了getWindow().superDisaptchTouchEvent(), 而我们知道getWindow()返回的是PhoneWindow,所以 间接的调用了PhoneWindow#superDispatchTouchEvent()

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

从上述方法可以看出,superDispatchTouchEvent调用了mDecor(不在此处详细介绍了)的superDispatchTouchEvent

DecorView#superDispatchTouchEvent()

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

DecorView继承自FrameLayout,所以super.dispatchTouchEvent(event)会调用到ViewGroup中的dispatchTouchEvent(event)方法。

Activity#onTouch()

前面通过源码跟踪了getWindow().superDispatchTouchEvent(ev)的调用过程,现在看一下onTouch()

public boolean onTouchEvent(MotionEvent event) {
    if (mWindow.shouldCloseOnTouch(this, event)) {
        finish();
        return true;
    }
    return false;
}

当一个点击事件未被Activity下的任何一个view消耗时,就会调用此方法。如: 处理发生在Window边界外的触摸事件。

Window#shouldCloseOnTouch()

public boolean shouldCloseOnTouch(Context context, MotionEvent event) {
    final boolean isOutside =
        event.getAction() == MotionEvent.ACTION_UP && isOutOfBounds(context, event)
        || event.getAction() == MotionEvent.ACTION_OUTSIDE;
    if (mCloseOnTouchOutside && peekDecorView() != null && isOutside) {
        return true;
    }
    return false;
}

主要是对于处理边界外点击事件的判断:是否是DOWN事件,event的坐标是否在边界内等。

ViewGroup 事件分发

从上面Activity事件分发机制可知,ViewGroup事件分发机制从dispatchTouchEvent()开始。

ViewGroup.dispatchTouchEvent()

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    // ...
 
    boolean handled = false;
 
    // 过滤掉不安全的事件响应
    if (onFilterTouchEventForSecurity(ev)) {
        final int action = ev.getAction();
        final int actionMasked = action & MotionEvent.ACTION_MASK;
 
        // 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();
        }
 
        // 检查是否需要拦截处理
        // Check for interception.
        final boolean intercepted;
        // DOWN事件或有触摸对象的情况下,检查是否需要做事件拦截处理
        if (actionMasked == MotionEvent.ACTION_DOWN
            || mFirstTouchTarget != null) {
            // 默认情况下是false,子view调用了父view的 requestDisallowInterceptTouchEvent() 改变
            final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
            // false的情况下,会调用onInterceptTouchEvent,根据intercepted的值进行判断是否需要拦截
            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 intercepted, start normal event dispatch. Also if there is already
        // a view that is handling the gesture, do normal event dispatch.
        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 isMouseEvent = ev.getSource() == InputDevice.SOURCE_MOUSE;
        final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0
            && !isMouseEvent;
        TouchTarget newTouchTarget = null;
        boolean alreadyDispatchedToNewTouchTarget = false;
        // 不拦截,不取消的情况下
        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;
 
            // 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;
                if (newTouchTarget == null && childrenCount != 0) {
                    final float x =
                        isMouseEvent ? ev.getXCursorPosition() : ev.getX(actionIndex);
                    final float y =
                        isMouseEvent ? ev.getYCursorPosition() : ev.getY(actionIndex);
                    // Find a child that can receive the event.
                    // Scan children from front to back.
                    // 对当前view下所有的子view根据z轴的值大小,从小到大进行排序
                    final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                    final boolean customOrder = preorderedList == null
                        && isChildrenDrawingOrderEnabled();
                    final View[] children = mChildren;
                    // 从后往前遍历所有child,将事件传递
                    for (int i = childrenCount - 1; i >= 0; i--) {
                        final int childIndex = getAndVerifyPreorderedIndex(
                            childrenCount, i, customOrder);
                        // 获取child
                        final View child = getAndVerifyPreorderedView(
                            preorderedList, children, childIndex);
                        // 如果child不能接收事件或者当前事件未在child内,则寻找下一个child
                        if (!child.canReceivePointerEvents()
                            || !isTransformedTouchPointInView(x, y, child, null)) {
                            continue;
                        }
                        // 第一次查找,由于mFirstTouchTarget为null,所以newTouchTarget也为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);
                        // 将事件分发到child, 如果child已消耗事件,则返回true
                        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();
                            // 事件被child消耗,那么会将child复制给 mFirstTouchTarget和 newTouchTarget, 并结束查找
                            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();
                }
                // 如果已经找到,newTouchTarget 不为空
                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;
                }
            }
        }
        // 如果 mFirstTouchTarget 为 null,表明没有找到需要消耗该事件的child
        // Dispatch to touch targets.
        if (mFirstTouchTarget == null) {
            // 传递child 为null后,会调用 super.dispatchTouchEvent(),进入view的事件分发中
            // No touch targets so treat this as an ordinary view.
            handled = dispatchTransformedTouchEvent(ev, canceled, null,
                                                    TouchTarget.ALL_POINTER_IDS);
        } else { // 找到了需要拦截的child, 进行后续事件处理
            // 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) {
                    // Down 事件 拦截处理
                    handled = true;
                } else {
                    final boolean cancelChild = resetCancelNextUpFlag(target.child)
                        || intercepted;
                    // 其他事件调用child分发
                    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;
            }
        }
        // ...
    }
    // ...
    return handled;
}

ViewGroup.onFilterTouchEventForSecurity()

当视图被隐藏或者窗口被遮挡时,过滤掉该事件响应。

public boolean onFilterTouchEventForSecurity(MotionEvent event) {
    //noinspection RedundantIfStatement
    // 当视图被隐藏或者窗口被遮挡时,过滤掉该事件响应
    if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
        && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
        // Window is obscured, drop this touch.
        return false;
    }
    return true;
}

ViewGroup.requestDisallowInterceptTouchEvent()

设置是否允许父view拦截触摸事件, true 不允许,false运行。

@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
 
    if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
        // We're already in this state, assume our ancestors are too
        return;
    }
 
    if (disallowIntercept) {
        mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
    } else {
        mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
    }
 
    // Pass it up to our parent
    if (mParent != null) {
        mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
    }
}

ViewGroup.onInterceptTouchEvent()

onInterceptTouchEvent的返回值决定当前viewGroup是否要对触摸事件进行拦截,如果为true,则进行拦截并终止事件往下传递,一般情况下不拦截。

public boolean onInterceptTouchEvent(MotionEvent ev) {
    if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
            && ev.getAction() == MotionEvent.ACTION_DOWN
            && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
            && isOnScrollbarThumb(ev.getX(), ev.getY())) {
        return true;
    }
    return false;
}

ViewGroup.buildTouchDispatchChildList()

child根据z轴值的大小进行从小到大排列(即 离用户的远近进行排列)。

public ArrayList<View> buildTouchDispatchChildList() {
    return buildOrderedChildList();
}
ArrayList<View> 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();
    // 遍历child,根据getZ()进行排列
    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;
}

ViewGroup.getTouchTarget()

根据child获取触摸的对象,第一次执行时,返回值为null。

private TouchTarget getTouchTarget(@NonNull View child) {
    for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
        if (target.child == child) {
            return target;
        }
    }
    return null;
}

ViewGroup.dispatchTransformedTouchEvent()

将当前事件进行child分发,当child为null时,调用super.dispatchTouchEvent(),返回true,代表事件已被消耗。

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

View 事件分发

ViewGroup.addTouchTarget()

获取TouchTarget并将其赋值给mFirstTouchTarget

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

View.dispatchTouchEvent()

touch事件最终会传递到ViewdispatchTouchEvent中,根据其返回值决定是否会消耗该事件。

public boolean dispatchTouchEvent(MotionEvent event) {
    // ...
    boolean result = false;
 
    if (mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onTouchEvent(event, 0);
    }
    // DOWN事件下停止上一次的滚动事件
    final int actionMasked = event.getActionMasked();
    if (actionMasked == MotionEvent.ACTION_DOWN) {
        // Defensive cleanup for new gesture
        stopNestedScroll();
    }
    // 过滤到不安全的事件响应
    if (onFilterTouchEventForSecurity(event)) {
        if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
            result = true;
        }
        // 先处理setOnTouchListener中的onTouch方法,如果返回true,则不再进行方法传递
        //noinspection SimplifiableIfStatement
        ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnTouchListener != null
                && (mViewFlags & ENABLED_MASK) == ENABLED
                && li.mOnTouchListener.onTouch(this, event)) {
            result = true;
        }
        // 如果mOnTouchListener == null  或 mOnTouchListener.onTouch() 为false,则会调用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;
}

补充点

action与actionMasked的区别:

相同点:
都表示此次MotionEvent的事件类型-手指按下/移动/抬起

不同点:
action 无法直接识别第二根手指的按下与抬起,而 actionMasked 可以。action 的类型有 按下、移动、抬起,而 actionMasked 有额外两种类型:
ACTION_POINTER_DOWN - “已经有手指按着了,又按下了新手指”
ACTION_POINTER_UP - “手指抬起了,但仍有其它手指按着”

使用建议:
action比actionMasked少了多指识别,适合"检测点击位置"、"记录按下时间"这种只涉及按下抬起的动作。
对于单指拖拽动作要确保用户只用一根手指,不会出现类似“按下第二根手指后抬起第一根手指,继续拖拽”这种临时多指的动作,否则位置会跳。
actionMasked比action更全面,无论处理简单拖拽还是复杂的多指事件都适用。

fun parseActionString(actionMasked: Int): String {
    return when (actionMasked) {
        MotionEvent.ACTION_DOWN -> "按下"
            MotionEvent.ACTION_POINTER_DOWN -> "按下(已有其它触摸点)"
            MotionEvent.ACTION_MOVE -> "移动"
            MotionEvent.ACTION_POINTER_UP -> "抬起(仍留其它触摸点)"
            MotionEvent.ACTION_UP -> "抬起"
            MotionEvent.ACTION_CANCEL -> "取消"
            else -> "未知"
            }
}

思维导图

Android事件分发机制