Android MotionEvent事件分发机制源码剖析

本文深入解析了Android系统中触摸事件从Activity到ViewGroup的分发过程,包括Activity、Window、DecorView和ViewGroup的事件处理机制,以及View对事件的简单处理流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android MotionEvent事件分发机制源码剖析

当点击事件发生时,首先Activity的dispatchTouchEvent被调用,Activity会把事件交给Window进行分发,Window又会交给DecorView进行分发,最后事件通过ViewGroup的dispatchTouchEvent一层层向下传递,如果所有子view都不消费事件,那么事件由View的dispatchTouchEvent进行处理。如果事件最后没有被任何view消费,将交给Activity的onTouchEvent处理,如果不消费,则事件被系统丢弃。所以,对触摸事件的分发,Activity,ViewGroup,View的做法是不一样的,这些步骤,都是系统预先实现好了的。

Activity对触摸事件的分发

先来看看Activity对触摸事件的处理

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

可以看出,Activity对触摸事件的处理很简单,即首先将事件交给Window进行分发,如果事件最后没有得到处理,那么,最后交由Activity的onTouchEvent()进行处理。

那么Window又是如何对事件进行分发的呢?

由于Window是一个抽象类,在创建Activity的过程中,系统给Activy创建的Window对象其实是一个PhoneWindow,在PhoneWindow里是将事件交给DecorView进行分发

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

而DecorView是PhoneWindow的一个私有类,它是一个FrameLayout,它将事件交给了父类进行处理,也就是ViewGroup进行分发。

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

所以,事件最后是交给了ViewGroup进行分发。

ViewGroup对触摸事件的分发

从Activity对事件的传递过程可以看到,触摸事件最后传递给了DecorView,而DecorView本身是一个FrameLayout,最后,DecorView调用了ViewGroup的dispatchTouchEvent()对事件进行分发。可以看出ViewGroup对事件的分发是通过dispatchTouchEvent()实现的。

我们知道,用户的一个完整的触摸操作,会触发一系列的MotionEvent,先后包括一次Down事件,一次或多次Move事件和一次Up事件。所以ViewGroup对事件的处理是从Down事件开始的。当收到Down事件时,首先,会初始化ViewGroup的触摸状态

// 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);
    //收到down事件时重置FLAG_DISALLOW_INTERCEPT
    resetTouchState();
}

在resetTouchState()里会重置ViewGroup的触摸状态,为新的触摸操作做准备

/**
 * Resets all touch state in preparation for a new cycle.
 */
private void resetTouchState() {
    clearTouchTargets();
    resetCancelNextUpFlag(this);
    mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
    mNestedScrollAxes = SCROLL_AXIS_NONE;
}

然后,判断是否拦截该事件。

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

当ViewGroup不拦截事件的时候,会遍历它的子View,判断View是否能够接收点击事件,是否点击事件落在其区域内,如果该View能够处理该事件,就将该事件传递给该View的dispatchTouchEvent()进行处理,如果该View的dispatchTouchEvent(),表示它已经处理了该事件,需要将该View添加到TouchTarget列表里,并且终止遍历。

    //如果ViewGroup不拦截
if (!canceled && !intercepted) {
    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<View> preorderedList = buildOrderedChildList();
            final boolean customOrder = preorderedList == null
                    && isChildrenDrawingOrderEnabled();
            final View[] children = mChildren;

            //遍历它的子View
            for (int i = childrenCount - 1; i >= 0; i--) {
                final int childIndex = customOrder
                        ? getChildDrawingOrder(childrenCount, i) : i;
                final View child = (preorderedList == null)
                        ? children[childIndex] : preorderedList.get(childIndex);
                //判断View是否能够接收点击事件,是否点击事件落在其区域内
                if (!canViewReceivePointerEvents(child)
                        || !isTransformedTouchPointInView(x, y, child, null)) {
                    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);
                //将事件交由子view处理,如果子View处理了,就直接终止向下传递,返回fasle
                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;
                }
            }
            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;
        }
    }
}

遍历完成后,如果没有任何View处理了该事件,则最后将传递给View自身进行处理。注意,传递的滴三个参数为null。

//如果没有任何子View处理过该事件,则交给自己处理
// Dispatch to touch targets
if (mFirstTouchTarget == null) {
    // No touch targets so treat this as an ordinary view.
    handled = dispatchTransformedTouchEvent(ev, canceled, null,
            TouchTarget.ALL_POINTER_IDS);
} 

View对事件的分发

从上面的分析可以知道,当一个View没有孩子,或者一个View的所有孩子的dispatchTouchEvent()均返回false的时候,事件会交给View自身进行处理也就是调用view.dispatchTouchEvent()方法进行处理。这就是View对事件的分发,该分发过程比ViewGroup对事件的分发要简单的多。过程如下

 public boolean dispatchTouchEvent(MotionEvent event) {
    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)) {
        //noinspection SimplifiableIfStatement
        ListenerInfo li = mListenerInfo;
        //如果OnTouchListener不为空,则交给onTouch处理,
        //如果onTouch返回true,则返回true;
        if (li != null && li.mOnTouchListener != null
                && (mViewFlags & ENABLED_MASK) == ENABLED
                && li.mOnTouchListener.onTouch(this, event)) {
            result = true;
        }
        //如果OnTouchListener没有处理事件,则交给view的onTouchEvent处理
        //,所以OnTouchListener的优先级高一些
        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对事件的处理过程十分简单,首先判断是否设置了OnTouchListener,如果设置了,执行onTouch方法,如果onTouch不消费事件,则交给onTouchEvent处理可见OnTouchListener的优先级要高一些

onClick和onLongclick的处理是在onTouchEvent里进行处理的。下面分析一下onTouchEvent()方法

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

    //一个View即使是DISABLED,只要它CLICKABLE或者LONG_CLICKABLE,也可以消费事件
    if ((viewFlags & ENABLED_MASK) == DISABLED) {
        if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
            setPressed(false);
        }
        // A disabled view that is clickable still consumes the touch
        // events, it just doesn't respond to them.
        return (((viewFlags & CLICKABLE) == CLICKABLE ||
                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
    }

    //执行触摸代理
    if (mTouchDelegate != null) {
        if (mTouchDelegate.onTouchEvent(event)) {
            return true;
        }
    }
    //只要CLICKABLE或者LONG_CLICKABLE就消费该事件
    if (((viewFlags & CLICKABLE) == CLICKABLE ||
            (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_UP:
                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) {
                        // 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();
                }
                break;

            case MotionEvent.ACTION_DOWN:
                mHasPerformedLongPress = false;

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

            case MotionEvent.ACTION_CANCEL:
                setPressed(false);
                removeTapCallback();
                removeLongPressCallback();
                break;

            case MotionEvent.ACTION_MOVE:
                drawableHotspotChanged(x, y);

                // Be lenient about moving outside of buttons
                if (!pointInView(x, y, mTouchSlop)) {
                    // Outside button
                    removeTapCallback();
                    if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                        // Remove any future long press/tap checks
                        removeLongPressCallback();

                        setPressed(false);
                    }
                }
                break;
        }

        return true;
    }

    return false;
}

从上面的分析可以看出

  1. 一个View即使是DISABLED,只要它CLICKABLE或者LONG_CLICKABLE,也可以消费事件
  2. 只要CLICKABLE或者LONG_CLICKABLE就消费该事件
  3. 对于onClick事件和onLongClick事件的触发时间不同,对于onLongClick事件,是在Down事件到来时发送一个延时的消息,当超过系统设的ViewConfiguration.getLongPressTimeout事件时,就会触发onLongclick()。如果长按消费了该事件,那么 mHasPerformedLongPress为true,onClick不会被触发,如果还没有超过180毫秒,那么在Up事件到来时,会移除长按mPendingCheckForLongPress对象,这样onLongClick就不会触发。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值