本篇文章主要是以Activity上的触摸事件为例,事件从InputReader,InputDispatcher传到ViewRootIpml开始谈起。
首先是时序图
其中最复杂的就是ViewGroup的dispatchTouchEvent方法将事件层层分发:
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
// If the event targets the accessibility focused view and this is it, start
// normal event dispatch. Maybe a descendant is what will handle the click.
if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
ev.setTargetAccessibilityFocus(false);
}
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
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);
resetTouchState();
}
// 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;
}
// If intercepted, start normal event dispatch. Also if there is already
// a view that is handling the gesture, do normal event dispatch.
if (intercepted || mFirstTouchTarget != null) {
ev.setTargetAccessibilityFocus(false);
}
// Check for cancelation.
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
// 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;
if (!canceled && !intercepted) {
// If the event is targeting accessiiblity focus we give it to the
// view that has accessibility focus and if it does not handle it
// we clear the flag and dispatch the event to all children as usual.
// We are looking up the accessibility focused host to avoid keeping
// state since these events are very rare.
View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
? findChildWithAccessibilityFocus() : null;
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 preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, 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();
}
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;
}
}
}
// 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);
} 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;
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;
}
}
// Update list of touch targets for pointer up or cancel, if needed.
if (canceled
|| actionMasked == MotionEvent.ACTION_UP
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
resetTouchState();
} else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
final int actionIndex = ev.getActionIndex();
final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
removePointersFromTouchTargets(idBitsToRemove);
}
}
if (!handled && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
}
return handled;
}
1
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();
}
首先一个完整的touch事件是以DOWN事件开始,以UP事件结束,中间可能贯穿多个MOVE事件,这个判断的作用是,判断一个新事件的开始,就将ViewGroup的成员变量mFirstTouchTarget的值置为null,mFirstTouchTarget指向的是消耗了touch事件的子View,如果没有子View消耗事件,该成员变量的值就是null的,这个值很重要,决定着后续MOVE和UP事件的传递流程
2
// 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是否调用onInterceptTouchEvent方法拦截事件,若拦截,则变量intercepted的值置为true,否则就是false。
第一个判断actionMasked == MotionEvent.ACTION_DOWN|| mFirstTouchTarget != null的意思是:
1)如果是DOWN事件,那么肯定走拦截的方法;
2)如果不是DOWN事件,则判断mFirstTouchTarget是否为null,即该ViewGroup的子View在之前的DOWN事件中是否消费了此次事件,如果消费了(即DOWN事件的onTouchEvent返回true,或者DOWN事件在dispatchTouchEvent分发的时候直接返回true),则此次非DOWN事件也会走到拦截的方法onInterceptTouchEvent中去,如果没有消费,则直接将intercepted置为true,不走该ViewGroup的拦截方法onInterceptTouchEvent方法,直接将intercepted置为true。
3
if (!canceled && !intercepted) {
// If the event is targeting accessiiblity focus we give it to the
// view that has accessibility focus and if it does not handle it
// we clear the flag and dispatch the event to all children as usual.
// We are looking up the accessibility focused host to avoid keeping
// state since these events are very rare.
View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
? findChildWithAccessibilityFocus() : null;
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);
//3.1
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 preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, 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;
}
//3.2
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();
}
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;
}
}
}
3中首先是两个判断,主要就是判断是DOWN事件,且没有拦截(intercepted为false)。
3.1中首先是判断该ViewGroup有没有child,如果没有就没有必要往下传递执行了,之后获取下点击的坐标和所有的子View,一个for循环遍历这个集合。注意这个循环是从ViewGroup的最上层的子View开始,依次往下遍历。
3.2 中首先判断子View能否接受point事件,并且这个point事件是否在这个view里面,如果有一个不满足,则continue,直接跳过本次循环;
然后调用dispatchTransformedTouchEvent方法,将事件在往子View分发,实现递归分发,知道最上层的view,如果在这个子View的某个child消费了事件(即DOWN事件的onTouchEvent返回true,或者DOWN事件在dispatchTouchEvent分发的时候直接返回true),则将newTouchTarget和mFirstTouchTarget都指向给子View(注意是一层一层的指向,即ViewGroup1指向ViewGroup2,ViewGroup2指向View1,而View1是真正消费事件的View),并且将alreadyDispatchedToNewTouchTarget置为true。
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);
}
一般newPointerIdBits和oldPointerIdBits都是1,child.hasIdentityMatrix是true的,因此:
1)如果传进来的child为null,则调用本身ViewGroup的父类View的dispatchTouchEvent方法处理事件。此方法中最后会调用到ViewGroup的onTouchEvent方法,这个后面再说。
2)如果传进来的child不为null,则调用child的dispatchTouchEvent方法,将事件继续往下传递。child如果是ViewGroup,则ViewGroup的分发dispatchTouchEvent是往子View传递,child如果是View,则View的dispatchTouchEvent是调用onTouchEvent去消费它。
5
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} 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;
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;
}
}
经过层层循环调用dispatchTouchEvent,当事件一直传递到最上层的View的父布局ViewGroup的dispatchTouchEvent时候,调用完3.2的代码循环完以后,执行了每个touch点内的child的dispatchTouchEvent,onTouchEvent方法后,执行5处的代码,
1)首先判断mFirstTouchTarget是否为null,如果为null,调用dispatchTransformedTouchEvent方法,此时调用4处代码,执行的是该ViewGroup的super.dispatchTouchEvent方法,内部会执行到该ViewGroup的onTouchEvent方法;
2)如果mFirstTouchTarget不为null,即某个子View消费了这个事件,则进入else分支的while循环中,判断alreadyDispatchedToNewTouchTarget && target == newTouchTarget是否成立,这个判断是用于区分DOWN事件和其他事件的,如果是DOWN事件,则条件满足,将handled置为true,如果是非DOWN事件,则进入else分支,找到这个target对应的View,调用dispatchTransformedTouchEvent向这个View分发事件。
注意:如果是Down之后的MOVE或者UP事件,执行ViewGroup的dispatchTouchEvent时,执行完1、2以后,直接执行5处的代码,如果之前的DOWN事件中判断子View没有消费掉事件,则直接执行此ViewGroup的onTouchEvent方法,事件到此ViewGroup就不往下传递,直接返回上层调用处了,若子View消费掉事件,进入else分支,将MOVE或者DOWN事件向目标View继续向下传递(即调用子View的dispatchTouchEvent方法)。
总结:
首先一个完整的touch事件是以DOWN事件开始,以UP事件结束,中间可能贯穿多个MOVE事件。Down和后面的Move,Up事件是紧密联系的。
1 ViewGroup在执行dispatchTouchEvent的时候的onInterceptTouchEvent方法会不会执行到,主要是看:
1)如果是Down事件,肯定会执行到。
2)如果是Down后的Move或者Up事件,看之前的Down事件中,子View有没有消费掉该事件,如果消费掉了该事件,则mFirstTouchTarget不为null,才会走onInterceptTouchEvent,如果在之前的Down事件中该ViewGroup没有子View消费事件,则不会走到onInterceptTouchEvent,而是将intercepted直接置为true。
从这里也可以感觉出,Down事件可以看出是否用来消费事件,为后面的Move和Up事件做准备的。
2)Move和Up事件不会走到3处的代码,而是直接走到5处的代码,判断mFirstTouchTarget是否为null,如果为null,表明在之前的Down事件中,没有子View消费事件,则进入dispatchTransformedTouchEvent方法,进入child==null的判断,此时调用ViewGroup自身的super.dispatchTouchEvent方法,里面会调用ViewGroup自身的onTouchEvent方法。
如果不为null,表明在之前的Down事件中子View消费了事件,此时,走到else判断,进入while循环中的else分支,调用dispatchTransformedTouchEvent将事件分发到消费了事件的子View处理。
2 对于注册了onTouchListener , onClickListener , onLongClickListerer的View处理
1)setOnTouchListener(),此回调是在View的dispatchTouchEvent方法中,在onTouchEvent方法之前,会判断有没有注册touch listener,如果有回调其中的onTouch方法,根据onTouch的返回值决定dispatchTouchEvent方法是否直接return。
2)setOnClickListener() 此回调是在View的onTouchEvent方法中case为ACTION_UP的情况下调用onClick方法,改方法没有返回值。
3)setOnLongClickListener()是在View的onTouchEvent方法中case为ACTION_DOWN情况下,发送一个延迟消息实现,在ACTION_UP中会删除这条消息。回调onLongClick方法,该方法有返回值,返回true后,在会掉完onLongClick后的ACTION_UP事件中不回调onClick,返回false之后,在ACTION_UP事件中依旧会回调onClick方法。
注意:设置setOnClickListener()和setOnLongClickListener()方法后,View在调用onTouchEvent方法时,就会局部变量clickable的值置为true,就会走到Switch方法,根据Action类型不同操作,一旦走到Switch,最后都会return true,即onTouchEvent返回true。这里就会影响到事件的分发。比如DOWN事件之后的MOVE UP事件都会传递到该View上来。