1,点击事件的传递规则
当一个MotionEvent产生后,系统需要把这个事件传递给一个具体的View,这个过程就是事件分发过程。下面是参与事件分发的三个重要方法的介绍:
public boolean dispatchTouchEvent(MotionEvent event)
用来进行事件分发。如果事件能够传递给当前View,那么此方法一定会被调用,返回结果受当前View和onTouchEvent和下级View的dispatchTouchEvent方法的影响,表示是否消耗掉当前事件。
public boolean onInterceptTouchEvent(MotionEvent ev)
用来判断是否拦截某个事件,如果当前View拦截了某个事件,那么同一个事件序列中,此方法不会再被调用,返回结果表示是否拦截当前事件。
public boolean onTouchEvent(MotionEvent event)
用来处理事件。返回结果表示是否消耗当前事件,如果不消耗,则在同一个事件序列中,当前View无法再次接收到事件。
如下伪代码可以表示以上三个方法的关系:
public boolean dispatchTouchEvent(MotionEvent event) {
boolean consume = false;
if(onInterceptTouchEvent(event)){
consume = onTouchEvent(event);
}else {
consume = child.dispatchTouchEvent(event);
}
return consume;
}
图1、事件分发流程图示
用语言描述如下:
1,当事件被触发时,首先接收到事件的是外ViewGroup,事件传入时,外ViewGroup会调用自身的onDispatchTouchEvent方法用来处理事件分发,接着调用onInterceptTouchEvent方法,这个方法会判断事件是否由调用者(外ViewGroup)消耗掉?若返回true,需要消耗,则接下来调用onTouchEvent方法处理事件;若返回false,不需要消耗这个事件,则该事件会向下继续传递给内ViewGroup。
2,内ViewGroup得到此次事件,同样效仿外ViewGroup,会先调用onDispatchTouchEvent方法处理事件分发,接着调用onInterceptTouchEvent判断事件消耗,若返回true,需要消耗,接下来执行onTouchEvent方法处理这个事件;若返回false,不需要消耗这个事件,则该事件继续向下传递,传递给了View。
3,当View接收到了这个事件的时候,注意,因为View是最后一级组件,或许是某一具体的组件如TextView,在View里是没有onInterceptTouchEvent方法的。所以,当View接收到这个事件时,先会onDispatchTouchEvent分发这个事件,接下来就是onTouchEvent处理这个事件。返回值为boolean类型。若View消耗此事件,返回true,若不处理,就返回false或者调用父类返回值,不处理的这事件。
4,若View不消耗此事件,Android事件分发机制会采取事件回传,即此事件再次被传给内ViewGroup,依次类推,内ViewGroup会向上传给外ViewGroup,最后直接传给屏幕,事件消失。
2,事件分发源码分析
1,Activity对点击事件的分发过程
一个点击操作首先会传递给Activity,由Activity的dispatchTouchEvent来进行事件分发,流程是Activity-->Window-->DecorView,下面是Activity内部的dispatchTouchEvent方法源码:
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
从上面的代码可以分析到,Activity获取Window调用事件分发,如果返回true,代表事件分发出去了,事件结束;如果返回false,说明该事件在往下传递的时候没有被消耗掉,此时就交给Activity的onTouchEvent方法处理。下面继续看一下Window的事件分发代码,但是Window是个抽象类,此时需要看Window的唯一实现类——PhoneWindow的代码:
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
PhoneWindow如上,mDecor其实是DecorView,下面继续追踪DecorView的代码:
private final class DecorView extends FrameLayout implements RootViewSurfaceTaker {
/* package */int mDefaultOpacity = PixelFormat.OPAQUE;
/** The feature ID of the panel, or -1 if this is the application's DecorView */
@Override
public final View getDecorView() {
if (mDecor == null) {
installDecor();
}
return mDecor;
}
}
我们知道,通过((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0)可以获取Activity设置的View,这个mDecor就是getWindow().getDecorView(),所以我们通过setContentView设置的布局view其实就是DecorView的一个子View。再看一下DecorView的源码,其实是继承自FrameLayout,FrameLayout是个ViewGroup也是一个View,也就是说,事件经过Actvity到Window到Decor几重传递,最终还是交给了View去处理,就是我们setContentView中设置的view,通常也是一个ViewGroup。
2,顶级View对事件的分发过程
上面从源码分析到,一次点击事件的传递最终会交给顶级view去处理,这里的顶级view大多数时候是一个布局,即ViewGroup,下面就对ViewGroup的dispatchTouchEvent方法的源码分段分析:
// 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是否拦截事件条件:事件类型为ACTION_DOWN或者mFirstTouchTarget != null。当ViewGroup的子元素成功处理事件时,mFirstTouchTarget会被赋值并指向子元素。换言之,当ViewGroup不拦截事件时,交给子元素处理,mFirstTouchTarget != null成立。反过来,当ViewGroup拦截了此事件,mFirstTouchTarget != null就不成立,那么后面的ACTION_MOVE和ACTION_UP等事件的到来,由于actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null这个条件为false,将导致ViewGroup的onInterceptTouchEvent不会再被调用,并且同一事件序列中的其它事件默认都由它来处理。
值得注意的是FLAG_DISALLOW_INTERCEPT标记位,这个标记位是通过子view调用requestDisallowInterceptTouchEvent方法来设置的。一般FLAG_DISALLOW_INTERCEPT一旦被设置后,ViewGroup将无法拦截除了ACTION_DOWN以外的其它点击事件。为什么是除了ACTION_DOWN以外呢?因为在ViewGroup分发事件时,如果是ACTION_DOWN就会重置FLAG_DISALLOW_INTERCEPT标记位,将导致子view中设置的是无效的。因此,当ACTION_DOWN事件到来时,ViewGroup总是会调用自己的onInterceptTouchEvent方法来询问自己是不是要拦截此事件。
下面就是当ACTION_DOWN事件到来时,FLAG_DISALLOW_INTERCEPT标志位被重置的源码:
// 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();
}
所以我们可以知道:1,当ViewGroup决定拦截事件时,那么后续的事件将会默认交给它处理并且不再调用它的onInterceptTouchEvent方法。2,FLAG_DISALLOW_INTERCEPT标记位是为了让ViewGroup不再拦截除ACTION_DOWN以外的事件。3,onInterceptTouchEvent并不是每次事件发生都会被调用的,只有dispatchTouchEvent才会每次都调用。
接下来,再看看ViewGroup不拦截事件,是怎样将事件下放给子View进行处理的:
final View[] children = mChildren;
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);
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);
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;
}
}
首先遍历ViewGroup里的所有子元素,然后判断子元素是否可以接收到点击事件。判断条件为子元素是否在播放动画和点击事件的坐标是否在子元素的区域内。如果满足这2个条件,那么会直接执行dispatchTransformedTouchEvent方法,这个方法的源码如下:
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
...
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
...
}
可以看到如果子元素child != null时,会直接调用child的dispatchTouchEvent方法继续分发事件。如果子元素的dispatchTouchEvent返回true,那么mFirstTouchTarget被赋值并且跳出for循环:
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
private TouchTarget addTouchTarget(View child, int pointerIdBits) {
TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
如果子元素的dispatchTouchEvent返回的是false,ViewGroup就会继续循环,把事件分发给下一个子元素(如果还有下一个子元素的话)。如果遍历了所以的子元素后事件还是没有被合适的处理:1,ViewGroup没有子元素。2,有子元素,还是子元素dispatchTouchEvent返回了false,这一般是在onTouchEvent里返回了false。这2种情况下,ViewGroup会自己处理点击事件。
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
}
在dispatchTransformedTouchEvent方法中最终还是调用super.dispatchTouchEvent(event)方法,事件最后被传递到View中dispatchTouchEvent中来处理。
3,View对点击事件的处理过程
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;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
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的dispatchTouchEvent方法的源码如上,View对事件的处理过程中,首先会判断有没有设置onTouchListener,如果onTouchListener的onTouch方法返回了true,那么onTouchEvent就不会得到调用,可见onTouchListener的优先级高于onTouchEvent,这样做的好处是方便在外界处理点击事件。
接下来分析一下onTouchEvent的源码,首先判断View是否是可用状态,如果是不可用状态下点击事件正常被View消耗掉。
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));
}
下面就是onTouchEvent对各种事件的处理,我们主要看一下ACTION_UP事件:
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;
}
从上面代码看出,只要View的CLICKABLE和LONG_CLICKABLE中有一个为true,那么它就会消耗这个事件,即onTouchEvent返回true。如果ACTION_UP事件发生时,会触发performClick方法,如果View设置了OnClickListener,那么performClick方法内部会调用它的onClick方法:
public boolean performClick() {
final boolean result;
final ListenerInfo li = mListenerInfo;
if (li != null && li.mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
li.mOnClickListener.onClick(this);
result = true;
} else {
result = false;
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
return result;
}
到此为止,完整的事件分发就分析完了。
ps:感谢任玉刚的《Android开发艺术探索》,这篇笔记只是对相关内容的简单总结,方便自己以后查看复习,如果大家觉得还可以,请购买正版书籍研读,非常不错!
网友评论