点击事件的传递规则
点击事件,说直接一点就是MotionEvent对象,事件的传递,就是将MotionEvent对象分发给不同的View来处理的过程,分发过程主要由三个重要方法组成:
public boolean dispatchTouchEvent(MotionEvent event);
-
public boolean onInterceptTouchEvent(MotionEvent ev);
(只存在于ViewGroup中,默认值为false) public boolean onTouchEvent(MotionEvent event);
先简单描述一下它们的关系:
首先,事件会传递给根ViewGroup
,它的dispatch方法被调用,在dispatch中会询问onIntercept
来决定该ViewGroup
是否消费该事件,如果返回true,那么该ViewGroup
就会消费掉该事件,将event交给当前ViewGroup
的onTouchEvent
来处理,事件结束。如果onIntercep
t返回了false,表示当前ViewGroup
不消费事件,会将它传递给他的子元素。然后子元素的dispatch方法执行,一直到事件被处理(onTouchEvent
返回值为true)。单一View没有onIntercept
,dispatchTouchEvent
会直接接收onTouchEvent
的返回值,返回true说明事件被当前View接收并处理了。
Activity#DispatchTouchEvent源码分析
所有的点击事件都是从Activity开始传递的,先看一下Activity中,dispatch方法的源码
/**
* Called to process touch screen events. You can override this to
* intercept all touch screen events before they are dispatched to the
* window. Be sure to call this implementation for touch screen events
* that should be handled normally.
*
* @param ev The touch screen event.
*
* @return boolean Return true if this event was consumed.
*/
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
首先,事件会传递到getWindow().superDispatchTouchEvent(ev)
,它的返回值决定了是否会调用Activity的onTouchEvent(ev)
。
我们继续看getWindow().superDispatchTouchEvent(ev)
的源码。Window的唯一实现类就是PhoneWindow(com.android.internal.policy.impl.PhoneWindow)
,直接查看superDispatchTouchEvent
方法:
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
代码很简单,直接调用了DecorView
的superDispatchTouchEvent
方法。DecorView
是PhoneWindow
的内部类,看一下代码:
private final class DecorView extends FrameLayout implements RootViewSurfaceTaker {
......
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
.......
看到这里,事件的传递流程其实就已经很清楚了:
Activity
首先接收到事件,通过一系列的调用,最终传递到了 DecorView
的 superDispatchTouchEvent
,DecorView
继承自FrameLayout
又继承自ViewGroup
,最终调用的方法实际上是ViewGroup
的dispatchTouchEvent(ev)
方法。由ViewGroup
来进行事件分发,如果分发成功,事件被消费,返回值为true。如果分发失败,事件仍然没有被消耗,返回false,事件就会交给Activity#onTouchEven
t处理。
我们只需要记住一点:事件传递从Activity开始,最终会传递到根ViewGroup的dispatchTouchEvent
。如果最终返回值为false,说明事件没有被拦截,最终会交给Activity的onTouchEvent
来处理。
ViewGroup的DispatchTouchEvent源码分析
源码很长,只截取了部分关键代码如下:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//标记事件是否已经被拦截
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
//@ 获取Action,Masked表示不考虑多点触控
final int actionMasked = action & MotionEvent.ACTION_MASK;
//@ 如果是ACTION_DOWN,清除所有初始状态,主要包括以下动作:
// 设置mFirstTouchTarget值为null
// 清除FLAG_DISALLOW_INTERCEPT标志,如果设置该标志为true,ViewGroup不拦截事件
if (actionMasked == MotionEvent.ACTION_DOWN) {
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// 用于标记事件是否被当前ViewGroup消费
final boolean intercepted;
//以下代码用来判断事件是否被当前ViewGroup消费,主要流程如下:
//-----------------------------------------------------------
//1.Down事件到来,必定会进入intercepted = onInterceptTouchEvent(ev);
//2.如果ViewGroup决定消费事件,那么intercepted被赋值为true
//3.intercepted被赋值为true之后,下面标记###--->1的if代码块不再执行,直接跳到 ###--->2
//4.mFirstTouchTarget赋值的语句在###--->3标记,包含在###--->1的if代码块内,所以,如果当前ViewGroup消费了事件,mFirstTouchTarget就一定是null
//5.继续看###--->2的代码,mFirstTouchTarget等于null,满足条件,调用dispatchTransformedTouchEvent方法,注意第三个参数为null
//6.查看dispatchTransformedTouchEvent,发现它调用了super.dispatchTouchEvent,也就是View的dispatchTouchEvent
//7.View的dispatchTouchEvent下文还会仔细讲解,它最终将事件交给了onTouch,onTouchEvent,onClick方法
//8.所以我们得出以下结论:如果ViewGroup的onInterceptTouchEvent,事件不会传递给子View,而是交给了自己的onTouch,onTouchEvent,onClick方法处理
//9.Down事件结束之后,MOve和Up到来时,actionMasked == MotionEvent.ACTION_DOWN为false,mFirstTouchTarget != null也是false,事件不会再进入onInterceptTouchEvent,而是直接交给当前ViewGroup处理了
//-----------------------------------------------------------
//如果onInterceptTouchEvent返回false,流程如下:
//1.Down事件到来,必定会进入intercepted = onInterceptTouchEvent(ev);
//2.ViewGroup不消费事件,intercepted被赋值为false,必定会进入###--->1出的if代码块
//3.运行到###--->4处,会对遍历子View,如果找到了拦截该事件的对象,在###--->3处的addTouchTarget方法内对mFirstTouchTarget进行赋值,并指向了当前ViewGroup的子元素。
//4.找到事件的拦截者并赋值给mFirstTouchTarget之后,继续向下运行到 ###--->5,此时mFirstTouchTarge!=null,执行else分支,在###--->6 处将事件交给了当前View的child来处理
//5.Down事件结束之后,MOve和Up到来时,mFirstTouchTarget仍然持有Target,所以下面的if满足mFirstTouchTarget != null,继续询问ViewGroup是否拦截事件
//6.MOve和Up的传递流程继续重复了Down事件的流程
/******************************************************************************/
/*/ 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;
/*/ }
/******************************************************************************/
......
// Update list of touch targets for pointer down, if needed.
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
###--->1 if (!canceled && !intercepted) {
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
......
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;
###--->4 for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, childIndex);
......
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();
###--->3 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();
}
......
}
}
//以下部分用于传递事件,到这里时已经找到了处理事件的对象,只是将事件交付给相应的对象来处理
// Dispatch to touch targets.
###--->2 if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
###--->5 } else {
// 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) {
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
###--->6 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;
}
通过对上边代码的分析,我们可以得到以下结论:
1.所有的ACTION_DOWN
都会进入onInterceptTouchEvent
方法,由ViewGroup
判断是否拦截,如果ViewGroup
拦截了ACTION_DOWN
,后续动作(ACTION_MOVE,UP)
都会交给ViewGroup
处理,不会再进入onInterceptTouchEvent
,这时候ViewGroup
的onTouchEvent
方法就会被调用,
2.如果ACTION_DOWN事件交给了ViewGroup的子View进行处理,后续动作(ACTION_MOVE,UP)仍然会进入onInterceptTouchEvent,有可能会被ViewGroup拦截。子元素可以通过mParent.requestDisallowInterceptTouchEvent方法限制ViewGroup消耗事件(不进入Intercept),但是对ACTION_DOWN不起作用。
3.ViewGroup拦截的事件会传递到View.dispatchTouchEvent,然后再由View传递给onTouch或onTouchEvent。ViewGroup并没有覆写onTouchEvent,onTouch等方法。
View#DispatchTouchEvent源码分析
这里的View通常指单一View,当事件传递到这里的时候,说明事件已经通过ViewGroup找到了对应的拦截方,View的DispatchTouchEvent只负责交付事件,所以代码也相对简单:
public boolean dispatchTouchEvent(MotionEvent event) {
boolean result = false;
......
if (onFilterTouchEventForSecurity(event)) {
//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方法返回了true,onTouchEvent就不会再执行了。
再来看onTouchEvent方法:
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;
}
}
如果View是Disabled状态,它仍然会消耗事件(CLICKABLE和LONG_CLICKABLE任一个为true)。
然后是代理的判断。继续往下看源码:
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 (!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;
从上边的代码可以发现,只要View的LONG_CLICKABLE或者CLICKABLE任一个为true(View的LONG_CLICKABLE默认为false,CLICKABLE针对不同view默认值不同),view就会消耗事件。只有在ACTION_UP的时候,才会执行onClick。
另外,setOnClickListener和setOnLongClickListener会自动将View的CLICKABLE,CLICKABLE设置为true。