Activity对事件分发的处理
点击事件产生之后,最先传递给当前Activity,由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方法进行处理。
public abstract boolean superDispatchTouchEvent(MotionEvent event);
跟进Window类可以看到,superDispatchTouchEvent是个抽象方法。
mWindow = new PhoneWindow(this);
查找Activity的成员变量mWindow的初始化过程,发现mWindow是PhoneWindow对象。于是查看PhoneWindow类的superDispatchTouchEvent方法。
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
这里PhoneWindow直接把点击事件交给mDecor进行分发。mDecor是一个DecorView对象,DecorView是window里的顶级View。在Activity里调用setContentView就是将layout的View设置为DecorView的子View。
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
而类DecorView继承自FrameLayout。superDispatchTouchEvent方法直接调用了父类的dispatchTouchEvent方法进行分发,即调用ViewGroup的dispatchTouchEvent方法。
ViewGroup对事件分发的处理
ViewGroup接收到事件之后,如果不拦截,就继续向子View分发。如果拦截,则调用onTouchEvent对事件进行处理,ViewGroup是View的子类,ViewGroup本身是没有onTouchEvent方法的,调用的View的onTouchEvent方法,因此拦截之后对事件的处理逻辑和View是一致的。
先从dispatchTouchEvent看起,以下判断是否拦截的部分。
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;
}
这里要调用onInterceptTouchEvent判断是否拦截要先满足两个if的条件。
首先是事件类型为ACTION_DOWN或者mFirstTouchTarget!=null,从后面源码可以知道当有子View成功处理了该事件的时候会调用addTouchTarget方法将mFirstTouchTarget赋值为该子View,也就是说mFirstTouchTarget!=null意味着这一系列的点击事件的ACTION_DOWN已经有子View进行处理了。因此如果ViewGroup拦截了ACTION_DOWN,后续的ACTION_MOVE、ACTION_UP等事件就会直接交给ViewGroup处理。
第二个if是FLAG_DISALLOW_INTERCEPT标志位,可以调用requestDisallowInterceptTouchEvent方法设置了该标志位。按照源码,假设子View处理了一系列事件的ACTION_DOWN,这时候mFirstTouchTarget!=null,默认是会调用ViewGroup的onInterceptTouchEvent方法判断是否拦截后续的ACTION_MOVE、ACTION_UP等事件的,而子View可以通过设置FLAG_DISALLOW_INTERCEPT标志位来拒绝ViewGroup插手这一系列事件。
而对ACTION_DOWN事件无效,因为在ACTION_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();
}
在分发ACTION_DOWN事件时,清除了mFirstTouchTarget和mGroupFlags。
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;
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 there is a view that has accessibility focus we want it
// to get the event first and if not handled we will perform a
// normal dispatch. We may do a double iteration but this is
// safer given the timeframe.
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
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;
}
// 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();
}
ViewGroup不拦截点击事件的时候,通过for循环遍历子View,通过canViewReceivePointerEvents和isTransformedTouchPointInView过滤掉不能接收事件的子View。canViewReceivePointerEvents判断View是否可见或者正在执行动画,isTransformedTouchPointInView判断点击是否在View的范围中,两个条件同时满足的View才可以接收到事件。
然后通过dispatchTransformedTouchEvent方法将事件分发到子View。
if (child == null) {
handled = super.dispatchTouchEvent(transformedEvent);
} else {
...
handled = child.dispatchTouchEvent(transformedEvent);
}
dispatchTransformedTouchEvent方法返回子View的处理情况。如果如果子View已经处理,返回true,则走进if分支调用addTouchTarget。并将标志位alreadyDispatchedToNewTouchTarget赋值为true。
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
将子View赋值给mFirstTouchTarget。
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
如果子View没有处理,调用dispatchTransformedTouchEvent(ev, canceled, null,TouchTarget.ALL_POINTER_IDS)方法,结合前面dispatchTransformedTouchEvent方法的代码可以知道当child为null时,调用super.dispatchTouchEvent方法,即View类的dispatchTouchEvent方法。强调一下,这个dispatchTouchEvent不是子View的方法,而是ViewGroup继承的View类的方法,因此这里是由ViewGroup处理事件。
View对事件分发的处理
从ViewGroup的dispatchTouchEvent方法分析可以知道,最后都会调用View类的dispatchTouchEvent方法进行处理。
public boolean dispatchTouchEvent(MotionEvent event) {
boolean result = false;
...
final int actionMasked = event.getActionMasked();
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)) {
result = true;
}
if (!result && onTouchEvent(event)) {
result = true;
}
}
if (!result && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
return result;
}
相对来说,View的dispatchTouchEvent方法比较短比较清晰。ListenerInfo是View中各种监听事件的聚合类,设置一些listener的时候就会初始化。
因此这里逻辑为:如果View设置了OnTouchListener,就先交给OnTouchListener处理,如果onTouchEvent返回true,就消费掉了事件。如果没有消费掉该事件,则调用View的onTouchEvent方法进行处理。接下来分段分析onTouchEvent的源码。
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == 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)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
}
从代码中可以看到,当View处于DISABLED状态时,如果CLICKABLE或LONG_CLICKABLE为true仍然会消费掉事件。
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
如果设置了代理,则交给代理处理,如果代理消费了事件,则返回true。否则继续往下走。
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
(viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
switch (action) {
case MotionEvent.ACTION_UP:
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
...
if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
...
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();
}
}
}
...
}
mIgnoreNextUpEvent = false;
break;
...
}
return true;
}
如果CLICKABLE或者LONGCLICKABLE为true时,最后默认return true,即默认消费掉touch事件。在ACTION_UP中,会触发post(mPerformClick)。
private final class PerformClick implements Runnable {
@Override
public void run() {
performClick();
}
}
PerformClick是Runnable的子类,run方法中调用了performClick方法。
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;
}
如果View设置了OnClickListener,则会调用onClick回调方法。