Android事件分发之ViewGroup
当事件传递到ViewGroup之后会调用ViewGroup的dispatchTouchEvent方法,这边文章我打算按照事件的类型和是否拦截来阐述事件在ViewGroup中是怎么处理的,因为我觉得只有说清楚每种类型的事件分别会怎么处理,才会让你对事件分发有一个清晰的认识.当手指触摸屏幕到离开屏幕会触发哪些类型的事件呢?平时可能我们听的最多的就是有MotionEvent.ACTION_DOWN,MotionEvent.ACTION_MOVE和MotionEvent.ACTION_UP.这里顺便问一下,如果有两个手指触摸到屏幕是不是会产生两个MotionEvent.ACTION_DOWN事件呢?我不知道这个问题有没有困扰过你,但是我之前确实是被这个问题困扰过.为了回答这个问题我们在做一个实验,实践出真知~
如上所示,我们继承LinearLayout并重写了dispatchTouchEvent方法,打印除MotionEvent.ACTION_MOVE之外其它事件(因为MOVE事件太多,这里我们先屏蔽一下),然后我们分别用手指A触摸屏幕,手指B再触摸屏幕,然后抬起手指A,再抬起手指B,所打印的log如下:
2021-08-12 17:16:21.919 30775-30775/com.example.phototest E/MyLinearLayout:: 当前事件类型:MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=431.0, y[0]=390.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=411889081, downTime=411889081, deviceId=2, source=0x1002, displayId=0 }
2021-08-12 17:16:23.136 30775-30775/com.example.phototest E/MyLinearLayout:: 当前事件类型:MotionEvent { action=ACTION_POINTER_DOWN(1), actionButton=0, id[0]=0, x[0]=431.0, y[0]=390.0, toolType[0]=TOOL_TYPE_FINGER, id[1]=1, x[1]=726.0, y[1]=748.0, toolType[1]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=2, historySize=0, eventTime=411890298, downTime=411889081, deviceId=2, source=0x1002, displayId=0 }
2021-08-12 17:16:26.704 30775-30775/com.example.phototest E/MyLinearLayout:: 当前事件类型:MotionEvent { action=ACTION_POINTER_UP(0), actionButton=0, id[0]=0, x[0]=431.0, y[0]=390.0, toolType[0]=TOOL_TYPE_FINGER, id[1]=1, x[1]=726.0, y[1]=748.0, toolType[1]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=2, historySize=0, eventTime=411893869, downTime=411889081, deviceId=2, source=0x1002, displayId=0 }
2021-08-12 17:16:28.456 30775-30775/com.example.phototest E/MyLinearLayout:: 当前事件类型:MotionEvent { action=ACTION_UP, actionButton=0, id[0]=1, x[0]=726.0, y[0]=748.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=411895622, downTime=411889081, deviceId=2, source=0x1002, displayId=0 }
通过日志我们可以清晰的看出当两个手指触摸屏幕时是不会触发两个MotionEvent.ACTION_DOWN事件的,第二根手指触摸的时候触发的事件是MotionEvent.ACTION_POINTER_DOWN事件,先抬起的手指触发的事件也不是MotionEvent.ACTION_UP事件而是MotionEvent.ACTION_POINTER_UP事件,最后抬起的手指触发的才是MotionEvent.ACTION_UP事件,这里注意区分一下,也就是说一个完整的事件序列有可能是一根手指的操作,也有可能是多根手指的操作,所以一个完整的事件序列总是以MotionEvent.ACTION_DOWN开始,一般中间可能会包含多个MotionEvent.ACTION_MOVE,MotionEvent.ACTION_POINTER_DOWN(多指操作),MotionEvent.POINTER_UP(多指操作),以MotionEvent.ACTION_UP或者MotionEvent.ACTION_CANCEL事件结束.这里我们通过日志对一个完整事件序列有了基本的认知,下面我们针对单指操作的所涉及的几种常见类型的事件来看看ViewGroup中如何处理事件的.这里我先贴一下dispatchTouchEvent的源码:
/**
* {@inheritDoc}
*/
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// Handle an initial down.
//@DOWN 处理最初的down事件,代表一个事件序列的全新开始,注释的意思大概是说:当开始一个新的手势时丢弃所有的前置状态,framwork 框架可能已经终止了前一个手势的up或cancel事件
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.
//@DOWN 判断是否拦截,这里的逻辑对所有类型的事件通用
final boolean intercepted;
//@DOWN 如果是一个Down事件或者mFirstTouchTarget != null时就需要判断是否拦截,mFirstTouchTarget是一个链表结构,链表的每一个节点存储一个已经接收并消费过事件的目标视图(子View),因为会有多指操作,所以是一个链表结构.
//@MOVE 当MOVE事件到来时,如果和该MOVE事件同属一个序列的DOWN事件被成功分发并消费的话,mFirstTouchTarget中肯定记录了消费事件的目标子View,所以肯定会进入判断是否需要拦截MOVE事件
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;
}
//@DOWN @MOVE 代码执行到这里,就确定了是否拦截该事件,我们看不拦截的情况(@DOWN ,@MOVE表示不拦截)
// 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;
//@DOWN MOVE不取消,不拦截进入执行
//@INTERCEPTED 事件被标志为要拦截,所以直接跳过if语句,到Dispatch to touch targets出继续执行
if (!canceled && !intercepted) {
//@DOWN 判断如果是DOWN事件或者是POINTER_DOWN事件(non-primary手指按下时)时会进入执行
//@MOVE MOVE事件不满足条件,所以不用进入遍历查找能接受事件的子View,(已经记录在mFirstTouchTarget链表中)
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<View> preorderedList = buildOrderedChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
//@DOWN for循环查找能够接受此事件的子View,注意这里有一个细节,for循环是从后面的添加的子View先判断,因为后面添加的视图可能遮盖前面添加的.经典
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;
}
//@DOWN 如果代码执行到这里,说明找到能接受这个事件的目标子View,然后再从链表中获取该子View所对应的touchTarget,如果没有则返回空,如果是down事件,这里会返回null
newTouchTarget = getTouchTarget(child);
//@A1 全新的down事件,这里不进入执行
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);
//@DOWN 这里通过调用dispatchTransformedTouchEvent方法将事件传递到给子View,如果事件被消费了这里就返回true,进入执行.
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();
//@DOWN down事件被成功消费,这里将创建该子视图对应的touchTarget加入到链表中,并作为链表的头节点(进入addTouchTarget方法可以看到)并且mFirstTouchTarget也指向该头节点
newTouchTarget = addTouchTarget(child, idBitsToAssign);
//@DOWN alreadyDispatchedToNewTouchTarget 置为true,代表事件已经成功传递并被消费并break跳出for循环,我们把目光放到for循环后面的逻辑继续追踪.
alreadyDispatchedToNewTouchTarget = true;
break;
}
}//for循环结束
if (preorderedList != null) preorderedList.clear();
}
//@DOWN down事件时,newTouchTarget不为空,不执行
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.
//@DOWN down事件时,mFirstTouchTarget不为空,直接进入else代码块
//@MOVE MOVE事件到来时,处理逻辑直接跳过遍历子View来到这里,因为mFirstTouchTarget != null,直接进入else代码块
//@INTERCEPTED 事件来到这里了,如果当前被拦截的事件时DOWN事件,说明事件一开始就被拦截了,所以mFirstTouchTarget == null成立,所以进入if语句,注释说得很清楚:“没有touchTarget,所以把自己V(ViewGroup)当做一个普通的View来对待,所以dispatchTransformedTouchEvent的参数child传入null”
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;
//遍历mFirstTouchTarget列表将事件进行分发
while (target != null) {
final TouchTarget next = target.next;
//@DOWN 当前事件是一个全新的down事件时满足这里的条件,说明事件已经成功传递被消费了,所以这里直接将handled置为ture.如此这般,down事件追踪到这里也算是有个结果了.
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
//决定事件是否进行拦截
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
//@MOVE 将cancelChild和目标子View相关信息传入 dispatchTransformedTouchEvent进行分发,如果事件被成功消费则将handled置位ture
//@INTERCEPTED 这里说明mFirstTouchTarget != null不为空,所以会将cancelChild置位true传入 dispatchTransformedTouchEvent中继续执行事件的分发工作。
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
//@INTERCEPTED 判断是否拦截了子View的事件,如果拦截了,这段逻辑会将该事件所属的touchTarget从mFirstTouchTarget中移除。
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.
//@UP 此处,如果事件被拦截了或者事件类型是MotionEvent.ACTION_UP会执行resetTouchState方法更新target链表
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;
}
为了说清楚处理的细节,将代码分段贴出来阐述我觉得多少有些不妥,所以我打算贴出整个方法的代码显得更连贯一些,在代码的字里行间做上记号和相应的注释,跟着记号和注释走一边看一边理解会容易理解的多,下面我们先说MotionEvent.ACTION_DOWN事件的分发,注释用DOWN开头
1.第一种类型:MotionEvent.ACTION_DOWN事件的传递(代码注释用@DOWN开头)
在上述代码中,跟着@DOWN作为开始的注释走就是MotionEvent.ACTION_DOWN不拦截的情况下分发给字View的逻辑。
2.第二种类型:MotionEvent.ACTION_MOVE事件的传递(代码注释用@MOVE开头)
当事件时MOVE事件时,如果mFirstTouchTarget不为空,则说明和该MOVE事件同属于一个事件序列的DOWN事件成功分发并被子View消费,而且该所对应的touchTarget会被记录在mFirstTouchTarget链表中,所以不会再次进入遍历子View的环节,而是直接进入遍历mFirstTouchTarget链表的环节根据是否拦截事件继续执行,UP事件的流程跟MOVE一样,只是当事件是UP事件时代表一个手势(一个完整的事件序列结束),所以会进入如下操作:
// 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);
}
/**
* Resets all touch state in preparation for a new cycle.
*/
private void resetTouchState() {
clearTouchTargets();
resetCancelNextUpFlag(this);
mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
mNestedScrollAxes = SCROLL_AXIS_NONE;
}
注释说得很清楚,重置所以触摸状态为新一轮的手势(事件序列)做准备。
以上我们说得都是事件没有被ViewGroup拦截并且被子View成功消费的情况,即dispatchTransformedTouchEvent方法都返回ture,下面我们看看返回false的情况如何:
3.被拦截的情况:intercepted = true(注释@INTERCEPTED)
在上路的注释追踪中,无论事件时拦截还是不拦截,具体的分发工作都交给了dispatchTransformedTouchEvent方法处理我们,我们看看这个方法内部的实现:
/**
* Transforms a motion event into the coordinate space of a particular child view,
* filters out irrelevant pointer ids, and overrides its action if necessary.
* If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
*/
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;
}
注意观察这段代码:
// 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.
//取消事件MotionEvent.ACTION_CANCEL是一种特殊情况,我们不需要执行任何转换和过滤,重点在于事件的类型,不在事件包含的其他类容,(比如事件的坐标参数等其他参数)
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;
}
代码中,如果cancel传入true,即该ViewGroup要拦截掉当前事件(有可能是DOWN ,MOVE等事件),这里会将当前事件包装的一个MotionEvent.ACTION_CANCEL事件,如果child == null,还记得什么情况下child会为空吗?
// 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);
}
答案就是把自己当成一个普通的View的时候为空,也就当前事件所属的事件序列没有被子View成功消费过,此时会调用handled = super.dispatchTouchEvent(event);最终会交给ViewGroup自己的onTouchEvent处理事件,如果子child不为空,就将ACTION_CANCEL发送个子View.
如果是其他的正常的事件,后续代码会通过一些转换后将事件通过handled = child.dispatchTouchEvent(event);将事件传递到下一层,如果下一层也是一个ViewGroup又将会按照ViewGroup的规则继续分发,如果此层层传递,最终将会将事件成功的传递给目标视图。
看看dispatchTransformedTouchEvent方法的注释:
/**
* Transforms a motion event into the coordinate space of a particular child view,
* filters out irrelevant pointer ids, and overrides its action if necessary.
* If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
*/
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {......}
注释大概是说将事件转换为具体的子视图的坐标空间,过滤掉不相干的ids,如果必要的话覆盖掉事件的类型(比如cancel为ture的时候会覆盖为CANCEL事件)如果子视图为空,这个事件会交由ViewGroup自己处理。
我们继续来看看拦截的一个特点,前面我们说当事件被拦截之后会将mfirstTouchTarget链表清空,所以该事件序列的后续事件到来时会首先会check for interception:
// 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;
}
可以看到actionMasked == MotionEvent.ACTION_DOWN和 mFirstTouchTarget != null两个条件都不满足,所以直接将intercepted置位ture.注释也说了,这里没有touch targets 并且这个事件不是一个最初的down事件,所以ViewGroup继续拦截掉该事件。这也就是ViewGroup事件拦截的特点,一旦拦截了该事件序列中的某一个事件,后续的事件将会默认拦截,即再也不会调用onInterceptTouchEvent方法判断,而是直接拦截。
不知道看到这里,你是否对ViewGroup处理事件的流程有没有一个总体的认识?如果你有什么疑问,欢迎在评论区留言,我会第一时间回复,咱们一起讨论一起成长。如果说得不对得地方,欢迎指正!