所谓View的事件分发,其实就是对MotionEvent事件的分发过程,即当一个MotionEvent产生了以后,系统需要把这个事件传递给一个具体的View,而这个传递的过程就是分发过程。

分发过程由三个重要的方法共同完成:dispatchTouchEvent、onInterceptTouchEvent和onTouchEvent,下面先简单介绍一下这些方法:

1、public boolean dispatchTouchEvent(MotionEvent ev) 用来进行事件的分发。如果事件能够传递给当前View,那么此方法一定会被调用,返回结果受当前View的onTouchEvent和下级View的dispatchTouchEvent方法的影响,表示是否消耗当前事件。

2、public boolean onInterceptTouchEvent(MotionEvent event) 在上述方法内部调用,用来判断是否拦截某个事件,如果当前View拦截了某个事件,那么在同一个事件序列当中,此方法不会被再次调用,返回结果表示是否拦截当前事件。

3、public boolean onTouchEvent(MotionEvent event) 在dispatchTouchEvent方法中调用,用来处理点击事件,返回结果表示是否消耗当前事件,如果不消耗,则在同一个事件序列中,当前View无法再次接收到事件。

当一个点击事件产生后,事件总是先传递给Activity,由Activity的dispatchTouchEvent()来进行事件分发,源码如下,路径android.app.Activity#dispatchTouchEvent:

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

根据Activity中的dispatchTouchEvent方法可以看到,里边会调用到getWindow()的superDispatchTouchEvent(ev),这里的getWindow()返回的是一个Window对象,而PhoneWindow又是抽象类Window在Android中唯一的实现,因此可以直接看PhoneWindow的superDispatchTouchEvent(ev),源码如下,路径com.android.internal.policy.PhoneWindow#superDispatchTouchEvent:

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

里边又调用到mDecor的superDispatchTouchEvent(event),源码如下,路径com.android.internal.policy.DecorView#superDispatchTouchEvent:

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

mDecor是一个DecorView对象,而DecorView继承自FrameLayout,FrameLayout继承自ViewGroup,FrameLayout本身没有重写dispatchTouchEvent方法,因此super.dispatchTouchEvent(event)最终就调用到了ViewGroup里,所以事件分发的核心部分是ViewGroup,我们暂时先放下这里,后边重点分析。

再回过头看下上述Activity的dispatchTouchEvent方法,最终会根据ViewGroup的dispatchTouchEvent的返回值决定后续流程,如果getWindow().superDispatchTouchEvent(ev)返回true,代表ViewGroup处理了该事件,直接返回,反之代表正在事件分发过程中没人处理这个事件,则会调用Activity的onTouchEvent方法,这就是整体的事件分发流程。

下面我们详细分析ViewGroup,刚才看到事件传递到了​ViewGroup的dispatchTouchEvent​ (event),那我们就看下它的源码,源码如下,路径android.view.ViewGroup#dispatchTouchEvent,代码略长,以下是精简了剩下核心流程的代码:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean handled = false;// 方法最后的返回值,该变量值表示是否处理了该事件。
if (onFilterTouchEventForSecurity(ev)) {// 出于安全原因,会过滤点击事件,在该方法中会对event的一些标志位进行处理,返回FALSE表示丢弃事件,返回TRUE表示继续处理。
final int action = ev.getAction();
// 在安卓源码中有大量的位操作,通过进行位操作限定标志位范围,再对其做判断,此处位操作的作用是保留action的末尾8bit位,其余置0,作为actionMasked。
final int actionMasked = action & MotionEvent.ACTION_MASK;

// 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);// 清空mFirstTouchTarget
resetTouchState();// 5、重置状态,如disallowIntercept
}

// Check for interception.
final boolean intercepted;// 该标志位表示是否拦截事件
if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) {// 1若该事件是ACTION_DOWN事件,或者事件已经被某个组件(mFirstTouchTarget)处理过
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;// 3允许拦截disallowIntercept标志位
if (!disallowIntercept) {// 4没设置不允许拦截disallowIntercept标志位
intercepted = onInterceptTouchEvent(ev);// 这里决定拦截intercepted为true,后续就会执行注释6处
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;//就是为了不拦截后续的非ACTION_DOWN事件
}
} else {// 2没有mFirstTouchTarget处理过,并且也不是初始的ACTION_DOWN事件,则拦截。
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}

if (!canceled && !intercepted) {// 7没拦截,由子View进行处理
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {//注意这里不执行ACTION_MOVE和ACTION_UP事件
final int childrenCount = mChildrenCount;
if (newTouchTarget == null && childrenCount != 0) {
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {// 8遍历ViewGroup所有子View
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, childIndex);
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {// 9调用dispatchTransformedTouchEvent,内部调用子View的dispatchTouchEvent()
newTouchTarget = addTouchTarget(child, idBitsToAssign);// 10给mFirstTouchTarget赋值
break;// 11跳出遍历子View
}
}
}
}
}
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {// 6可能没有子View或者所有的子View都不处理该事件或者是ViewGroup拦截了事件

// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {//有子View处理了ACTION_DOWN,ACTION_MOVE和ACTION_UP会执行这里
// 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) {// alreadyDispatchedToNewTouchTarget为true就说明了mFirstTouchTarget被赋值了,所以事件已经交给子View处理了,这里就返回true
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {//设置了FLAG_DISALLOW_INTERCEPT,后续ACTION_MOVE和ACTION_UP会执行子View的dispatchTouchEvent()
handled = true;
}
if (cancelChild) {
if (predecessor == null) {
mFirstTouchTarget = next;
} else {
predecessor.next = next;
}
target.recycle();
target = next;
continue;
}
}
predecessor = target;
target = next;
}
}
}
return handled;
}

首先看下注释1处的mFirstTouchTarget,那么mFirstTouchTarget != null是什么意思呢?这个从后面的代码逻辑可以看出来,当事件由ViewGroup的子元素成功处理时,mFirstTouchTarget会被赋值并指向子元素。

也就是说,当ViewGroup不拦截事件并将事件交由子元素处理时mFirstTouchTarget才不为null。反之,一旦事件由当前ViewGroup拦截时,mFirstTouchTarget就是null,这样当ACTION_MOVE和ACTION_UP事件到来时,由于mFirstTouchTarget是null,将导致执行注释2处代码,ViewGroup的onInterceptTouchEvent不会再被调用,并且同一序列中的其他事件都会默认交给它处理。

当然,这里有一种特殊情况,就是上述注释3处的FLAG_DISALLOW_INTERCEPT标记位,这个标记位是通过ViewGroup的requestDisallowInterceptTouchEvent方法来设置的,一般用于子View中。FLAG_DISALLOW_INTERCEPT一旦设置后,ViewGroup将无法拦截除了ACTION_DOWN以外的其他点击事件。为什么说是除了ACTION_DOWN以外的其他事件呢?这是因为ViewGroup在分发事件时,如果是ACTION_DOWN就会重置FLAG_DISALLOW_INTERCEPT这个标记位,具体代码是执行注释5处代码,将导致子View中设置的这个标记位无效。因此,当面对ACTION_DOWN事件时,ViewGroup总是会调用自己的onInterceptTouchEvent方法来询问自己是否要拦截事件,也就是一定会执行注释4,。因此子View调用requestDisallowInterceptTouchEvent方法并不能影响ViewGroup对ACTION_DOWN事件的处理,所以FLAG_DISALLOW_INTERCEPT就是为了不拦截后续的非ACTION_DOWN事件设计的。

如果ViewGroup决定拦截ACTION_DOWN事件,就会执行注释6处的​dispatchTransformedTouchEvent​方法,暂时先不管dispatchTransformedTouchEvent内部,下面统一分析,mFirstTouchTarget就是null,后续的非ACTION_DOWN事件将会默认交给它处理并且不再调用它的onInterceptTouchEvent方法

如果ViewGroup不拦截事件的时候,事件会向下分发交由它的子View进行处理,具体执行注释7处,然后在注释8处,遍历ViewGroup的所有子元素,然后判断子元素是否能够接收到点击事件。是否能够接收点击事件主要由两点来衡量:子元素是否在播动画和点击事件的坐标是否落在子元素的区域内。如果某个子元素满足这两个条件,那么事件就会传递给它来处理,然后也会调用到​dispatchTransformedTouchEvent​方法,暂时先不管dispatchTransformedTouchEvent内部,下面统一分析,如果dispatchTransformedTouchEvent返回了true,就会执行注释10处,调用addTouchTarget()方法,内部会完成mFirstTouchTarget的赋值,并且在注释11处终止对子元素的遍历,那我们就看下addTouchTarget()的源码,源码如下,路径android.view.ViewGroup#addTouchTarget

private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;// 单链表结构
mFirstTouchTarget = target;// 这里就会完成mFirstTouchTarget的赋值
return target;
}

mFirstTouchTarget是否被赋值,将直接影响到ViewGroup对事件的拦截策略,如果mFirstTouchTarget为null,那么ViewGroup就默认拦截接下来同一序列中所有的点击事件,这一点在前面已经做了分析。

如果遍历所有的子元素后事件都没有被合适地处理,这包含两种情况:第一种是ViewGroup没有子元素;第二种是子元素处理了点击事件,但是在dispatchTouchEvent中返回了false,这一般是因为子元素在onTouchEvent中返回了false。在这两种情况下,ViewGroup会自己处理点击事件,同样也会调用到注释6处代码执行​dispatchTransformedTouchEvent​方法,就如同ViewGroup自己拦截了事件,自己来处理。

上面提到ViewGroup自身拦截或子View没有处理,还是需要ViewGroup自身处理,都会调用dispatchTransformedTouchEvent(),传入的参数child为null,如果是没拦截,遍历到了子View,也会调用dispatchTransformedTouchEvent(),传入的参数child就是遍历出来的子View本身,因此下面看下dispatchTransformedTouchEvent(),源码如下,路径android.view.ViewGroup#dispatchTransformedTouchEvent

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

提取核心代码可以看到主要执行了

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

也就是说如果传入的child为null,会return super.dispatchTouchEvent(),也就是会调用ViewGroup的父类View的dispatchTouchEvent(),这样点击事件开始交由View来处理;如果child不为null,就调用子view本身的dispatchTouchEvent(),如果子View不是ViewGroup,则也会交由View的dispatchTouchEvent()处理这个事件,如果子View是ViewGroup,那就开启新一轮的事件分发,就又回到了上面分析的ViewGroup的dispatchTouchEvent()方法

然后事件到了​View的dispatchTouchEvent​ (MotionEvent event),直接上源码如下,路径android.view.View#dispatchTouchEvent

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)) {
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)) {// 1判断有mOnTouchListener并且mOnTouchListener返回true
result = true;
}

if (!result && onTouchEvent(event)) {// 2如果上述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对点击事件的处理过程就比较简单了,因为View(这里不包含ViewGroup)是一个单独的元素,它没有子元素因此无法向下传递事件,所以它只能自己处理事件。注释1处,可以看出View对点击事件的处理过程,首先会判断有没有设置OnTouchListener,如果OnTouchListener中的onTouch方法返回true,那么onTouchEvent就不会被调用,可见OnTouchListener的优先级高于onTouchEvent,这样做的好处是方便在外界处理点击事件。如果没设置OnTouchListener,就会执行View的onTouchEvent(MotionEvent event)方法,代码精简如下,源码路径android.view.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;// 1判断View是否可点击,包括点击或长按事件

if ((viewFlags & ENABLED_MASK) == DISABLED) {// 2View处于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) {//如果设置了TouchDelegate这里会执行TouchDelegate的onTouchEvent,类似TouchEventListener
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}

if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {//3clickable
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();//4performClick()
}
}
}

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;//5表示消耗了事件
}

return false;
}

onTouchEvent首先在注释1处判断View是否是clickable状态,包括点击和长按,然后注释2处,View处于不可用状态下点击事件的处理过程,可以看到,不可用状态下的View照样会消耗点击事件,尽管它看起来不可用。

然后在注释3处,判断是clickable的,也就是说只要View的CLICKABLE和LONG_CLICKABLE有一个为true,那么它就会消耗这个事件,即onTouchEvent方法返回true,也就是注释5,结合上述描述,不管View是不是DISABLE状态,都会消耗这个事件。

然后就是当ACTION_UP事件发生时,会触发performClick方法,这就是给如果View设置了OnClickListener,会执行注释4处代码,那么performClick方法内部会调用它的onClick方法。

最后

小编在网上收集了一些 Android 开发相关的学习文档、面试题、Android 核心笔记等等文档,希望能帮助到大家学习提升,如有需要参考的可以直接去我访问查阅。

View事件分发机制_事件分发机制