在View的事件分发(Activity篇)中我们分析了Touch事件由Activity最后分发到ViewGroup中的dipatchTouchEvent()方法中的过程,这篇博客主要大家分析ViewGroup中dispatchTouchEvent方法中处理Touch事件的逻辑,由于源代码比较复杂,所以直接采取注释代码的方式解读源代码。如果对源代码无兴趣可以直接跳到结尾获得,这段源代码我们所获得的关于ViewGroup的Touch事件分发的知识点。
@Override
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.
//MotionEvent为ACTION_DOWN取消和清除TouchTargets、重置TouchState、FLAG_DISALLOW_INTERCEPT标志位,该标志位默认为false
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.
//该方法会重置mFirstTouchTargets为null
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// Check for interception.
final boolean intercepted;
//MotionEvent为ACTION_DOWN或FirstTouchTarget不为null(一个Touch事件开始的ACTION_DOWN或者该事件已经交给子View去处理(FirstTouchTarget不为null)
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
//FLAG_DISALLOW_INTERCEPT(该标志位的设立为不允许当前View/ViewGroup拦截事件,但是改标志为当MotionEvent为ACTION_DOWN时会被重置(25行代码处,当MotionEvent为ACTION_DOWN时重置))
----------
//1、此处我们得出一个重要结论:只要不是ACTION_DOWN事件,那么FLAG_DISALLOW_INTERCEPT该标志位可以干涉ViewGroup不拦截这个事件,在这种情况下,onInterceptTouchEvent()这个方法将失去作用。普通情况是否拦截当前事件是由onInterceptTouchEvent(true拦截/false不拦截)这个方法决定。
----------
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
//如果设置了标志位拦截该事件,最终还要询问onInterceptTouchEvent方法是否拦截该事件
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
//此处的逻辑为没有设置标志位该ViewGroup拦截事件,所以该ViewGroup拦截该事件
intercepted = false;
}
} else {
//此处的逻辑说明该事件已经交给该ViewGroup处理,事件为ACTION_MOVE/ACTION_UP,所以拦截标志为(intercepted)true
// 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;
//此处为重置newTouchTarget为null
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
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.
//在记录表里面寻找一个能够接收事件的View,从前往后扫描子View
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.
//寻找能够获得焦点的Children(View)
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
//这个Child(View)能够接受到点击事件,并且左边在这个View的范围内
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
//寻找指定的child(View)的TouchTarget
newTouchTarget = getTouchTarget(child);
//如果newTouchTarget不为空,说明已经有View消耗了这个Touch事件,有了相应的TouchTarget,那就直接跳出这个循环
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);
//正常的如果找不到newTouchTarget,即是这个Touch事件还没有被子View消耗,有相应记录的TouchTarget,即调用dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)传递给子View,然后根据返回值去判断子View是否消耗的这个Touch事件
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
//子View消耗了这个事件那么就将子View所在View的数组中的位置记录下来,即是mLastTouchDownIndex这个数值,然后跳出这个循环(如果有先前顺序列表就去列表里面找,没有就用先前View(Children)所在数组的数值)
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();
//将接收这个事件的Child(View)赋值给mFirstTouchTarget,并将原来的mFirestTouchTarget给TouchTarget列表的下一个,并且跳出这个循环,因为事件被Child(View)消耗了,所以newTouchTarget依然也有值
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();
}
//该种情况是,如果事件不是ACTION_DOWN,mFisrtTarget就不会被重置为null,但是如果要newTouchTarget有值,必须是事件在Child(View)里面被消耗了,简单概括事件被分下去了,,却没被消耗,于是就把事件添加进最近的TouchTarget里面去了
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;
}
}
}
----------
2、//mFirstTarget即是当事件分发都没有分发给子View,如果没有子View接收这个事件,那么后续的所有事件都会交给ViewGroup自己
----------
//事件直接没有被分给Child(View),所以调用ViewGroup的dispatchTransformedTouchEvent(ev, canceled, null,TouchTarget.ALL_POINTER_IDS)自己去处理这个事件
// 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
这是将事件分发给子View的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.
//如果子View为空就会调用View的dispatchTouchEvent方法去处理
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());
}
//子View是ViewGroup就调用ViewGroup如果子View是View就调用View的
handled = child.dispatchTouchEvent(transformedEvent);
}
// Done.
transformedEvent.recycle();
return handled;
}
结论:
1、只要不是ACTION_DOWN事件,那么FLAG_DISALLOW_INTERCEPT该标志位可以干涉ViewGroup不拦截这个事件,在这种情况下,onInterceptTouchEvent()这个方法将失去作用。普通情况是否拦截当前事件是由onInterceptTouchEvent(true拦截/false不拦截)这个方法决定。
2、事件分发是有父到子进行分发的
3、如果子View不消耗事件就会重新交给父View处理
4、如果决定了拦截一个事件,那么整个事件都会交给这个ViewGroup处理
5、分发给子View的事件,如果是View就会调用View的dispatchTouchEvent(),是ViewGroup就会调用ViewGroup的dispatchTouchEvent()