Activity中的视图以View树的形式来呈现。当触控手机屏幕时,事件从Activity、Window、根View依次进行传递,然后根View又依次往下传递给子View。如果某个子View对事件进行了消耗,那么事件将不在继续向下传递。
一:事件分发中几个重要的方法
-
public boolean dispatchTouchEvent(MotionEvent ev)
事件传递给ViewGroup时,该方法将被执行,对进行事件的分发,返回结果表示是否消耗该事件。 -
public boolean onInterceptTouchEvent(MotionEvent ev)
该方法在dispatchTouchEvent内部调用,用来判断ViewGroup是否应该对事件进行拦截,如果进行拦截,那么事件将无法传递给ViewGroup中的子View。返回结果表示是否拦截该事件。 -
public boolean onTouchEvent(MotionEvent ev)
在dispatchTouchEvent方法中调用,用来处理子View都没有对事件进行处理,或者拦截了事件,那么ViewGroup将自己进行处理。返回true表示消耗了该事件。
二:几个读代码时需要理解的点
- 手指按下、移动、起来 称为一次事件序列
- 触摸事件只能被一个View进行处理或者说消耗
- 当按下的事件没有被ViewGroup中的任何一个子View所处理,那么同一事件序列中的其他MOVE、UP事件都不会在传递给子View进行判断是否要处理事件,直接交给自己来处理
上面这些点都能在下面的代码中得到答案
三:ViewGroup的事件分发流程
下面是ViewGroup的dispatchTouchEvent()方法,该方法即是ViewGroup的事件分发过程,在里面添加了重要的注释。先看个大概,下面我将一一分析。
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
...
boolean handled = false;
//过滤掉View被Window窗口遮挡的触摸事件
if (onFilterTouchEventForSecurity(ev)) { // ------ 步骤1 ------
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// 处理Action_Down的事件, ------ 步骤2 ------
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.
//清除touchTarget,重置触摸相当的标志位
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// Check for interception ------ 步骤3 ------
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
//------ 步骤4 ------
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) { //------ 步骤5 ------
...
//这里要注意只有down 事件,还有其他俩个条件才能进入,并对ViewGroup的子View进行
//遍历。假设down事件来时,被某一子View处理了,那么接下来的该事件序列的Move、UP
//都不在会遍历ViewGroup,而是根据down时记录的mFirstTouchTarget对象,利用其中的
//子View。直接将事件传递给该子View
//------步骤 6 ------
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
//actionIndex 表明是否为多点触控,0为单点,1为多点触控
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.
//将ViewGroup的所有子View,根据View的Z轴大小进行排序,Z轴越高,排在前面
//这里考虑到View层级越靠前,越有机率被View进行处理
final ArrayList<View> preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
//该For循环,从排好序的List中,依次拿出View,判断当前View是否位于触摸事件的范围
//如果分发给View的事件被处理之后,那么mFirstTouchTarget就会被赋值,并跳出循环
//------步骤 7------
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;
}
// ------- 步骤8 -------
//判断该子View是否可以收到该触摸事件,如果不能直接去判断下一个子View
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);
//如果子View在触摸范围内,然后将事件down传递给该子View,如果该子View这里返回true
//表示消耗了事件,跳出该循环,不在遍历其他子View。 // ------- 步骤9 --------
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();
//mFirstTouchTarget就是这里被创建的
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. ------- 步骤10 --------
if (mFirstTouchTarget == null) {
//这里是ViewGroup的所有子View都没有处理该事件时,那么ViewGroup就会
//自己进行处理。
// 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) {
//这里是前面Down事件时,View消耗了事件会走进这里
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
//这里是ViewGroup中如果有View对down处理了事件,从mFirstTouchTarget的拿出保存的View。
//将MOVE、UP事件传递给该View进行处理 ----- 步骤11 -----
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:过滤到ViewGroup被Window窗口遮挡的事件,不进行传递逻辑的判断
步骤2: 这里对Action_Down事件进行处理,清除touchTarget,重置触摸相关的标志位。这里可以看出每次Down事件就是一次新的事件序列。同一个事件序列中MOVE、UP事件将依赖DOWN事件,后面我们在提。
步骤3:这里要 ViewGroup是否拦截事件,子View能否收到触摸事件在这里进行了判断。 可以看到如果事件为Action_DOWN或者mFirstTouchTarget不为空。将会调用onInterceptTouchEvent()方法判断是否拦截。
mFirstTouchTarget当🈶️子View对DOWN事件进行消耗时,将会创建TouchTarget对象,其中持有接收该事件的View的引用。若没有子View对DOWN事件进行消耗,那么mFirstTouchTarget将为空,当同一事件的MOVE、UP来时,将执行"intercepted = true",即MOVE、UP都不会在传递给子View进行判断处理是否消耗该事件了
步骤4: 会对GroupFlags 的FLAG_DISALLOW_INTETCEPT标记为进行判断,当设置了该标志位时,disallowIntercept为true。那么将不会执行onInterceptTouchEvent(ev)方法,执行intercepted = false。 这时候即使ViewGroup的onInterceptedTouchEvent()方法中返回true,但因为这里的标记为将不会被执行。所以起到了不允许拦截事件传递给子View的作用
步骤5: 没有取消,没有拦截,那么接下来就是传递给子View了。首先遍历ViewGroup中的子View,把事件传递给子View,让子View去进行处理是否消耗该事件
步骤6: 这里要注意只有ACTION_DOWN又或是另外俩中情况才会进行遍历子View,然后把事件传递给子View
步骤7: 进行ViewGroup的遍历,这里遍历的List是已经排好序的。根据View的Z轴大小进行排序,Z轴越高,排在前面这里考虑到View层级越靠前,越有机率被View进行处理
步骤8: 判断该子View是否可以收到该触摸事件,如果不能直接去判断下一个子View。View能否收到动画是判断View是否显示以及触摸坐标是否落在View上
步骤9: dispatchTransfromedTouchEvent方法为
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
...
// 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;
}
方法参数child不为空,调用child.dispatchTouchEvent()方法,这样触摸事件就传递给了子View进行处理。如果子View中该方法返回了true,表示消耗了该事件。然后使用addTouchTarget()方法创建了TouchTarget对象。前面提到的mFirstTouchTarget就是这里被创建的,然后跳出for循环。如果没有一个在触摸范围内的子View的dispatchTouchEvent方法返回true,则mFirstTouchTarget就不会被赋值。
步骤10: 处理mFirstTouchTarget为null的情况,也就是ViewGroup中没有子View消耗该事件,那么调用dispatchTransformedTouchEvent()方法,这里child传參传为null,执行super.dispatchTouchEvent(transformedEvent); ViewGroup的父类为View,则调用View的dispatchTouchEvent()。也就是ViewGroup自己来处理该事件。
步骤11: 另外一种情况是mFirstTouchTarget不为空,也就是有子View消耗了事件。如果事件为DOWN,View消耗了事件,前面将alreadyDispatchToNewTouchTarget设置为ture,这里就会进去ialreadyDispatchToNewTouchTarget f 语句内,handler为true。 如果事件为MOVE、UP事件时,且mFirstTouchTarget不为空,步骤6则不会执行,直接会走到步骤11处,dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)。取出mFirstTouchTarget中保存的View,传入该方法。
概括为:当DOWN事件被子View消耗时,会将该子View保存到mFirstTouchTarget,当同一事件序列中其他MOVE、UP事件到来时,不用在去遍历ViewGroup中的子View.直接将MOVE、UP事件传递给mFirstTouchTarget中保存的子View
四:流程图
ViewGroup事件分发 View事件分发五:总结
-
当事件传递给ViewGroup时,首先会判断ViewGroup是否拦截事件传递给子View,如果不拦截,则会把落在子View区域的触摸事件传递给子View进行事件分发(如果子View是ViewGroup,则又会经历相同的步骤,进行事件分发),子View事件分发之后返回为false,表示没有消耗,则传递给其他子View。如果ViewGroup中没有一个子View对事件进行消耗,则ViewGroup会自己进行处理。
-
触摸事件只能被一个View进行处理或者说消耗
-
当ViewGroup对DOWN事件进行传递时,没有子View对该事件进行消耗,那么同一事件序列的MOVE、UP则不会在分发给子View了,这是由于按下的时候没有子View进行处理,则其他事件就直接自己处理了
-
如果DOWN事件进行分发时,有子View对事件进行消耗,同一事件序列的MOVE、UP将直接传递给该子View进行处理
-
每一次DOWN都是事件分发的重新开始,DOWN事件来时会清除
FLAG_DISALLOW_INTERCEPT 标记位和mFirstTouchTarget -
子View 可以设置 ViewGroup的FLAG_DISALLOW_INTERCEPT 标记位,让ViewGroup无法拦截同一事件中的MOVE、UP事件
网友评论