上一篇讲了view的事件分发,比较简单。接下来看看稍微复杂一点的ViewGroup。
我们还是先用log看一下主要方法是如何执行的:
ViewGroup事件分发的核心内容主要在dispatchTouchEvent()这个方法中。点进去看一下源码,代码有点长,在关键部分注释一下:
@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;
//1.没有被遮挡
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.
//2.清空异常及已有状态 给所有之前选择出的Target发送Cancel事件,
//确保之前Target能收到完整的事件周期;
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// Check for interception.
final boolean intercepted;
//3.如果是ACTION_DOWN事件,或者已经将之前的ACTION_DOWN事件分发给childview
//注:当ViewGroup的childview成功处理时,会将mFirstTouchTarget 指向该childview
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
//4.是否禁止拦截
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
//5.如果没有禁止拦截
if (!disallowIntercept) {
//6.判断是否拦截,也就是onInterceptTouchEvent的返回值
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
}
//7.如果禁止拦截,当然就不拦截了
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.
// 8.在这种情况下,actionMasked != ACTION_DOWN && mFirstTouchTarget == null
// 第一次的down事件没有被此ViewGroup的children处理掉(要么是它们自己不处理,要么是ViewGroup从一
// 开始的down事件就开始拦截),则接下来的所有事件
// 也没它们的份,即不处理down事件的话,那表示你对后面接下来的事件也不感兴趣
//意味着上一次ACTION_DOWN 事件没有分发下去,所以后续事件不再询问,直接拦截
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.
//9.此touch事件是否cancel
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
// Update list of touch targets for pointer down, if needed.
//10.是否拆分事件,与多点触控有关,默认拆分
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
//11.找到的childview,接下来ViewGroup判断要将此touch事件交给他处理
TouchTarget newTouchTarget = null;
//12.down或pointer_down事件已经被处理
boolean alreadyDispatchedToNewTouchTarget = false;
//13.没有cancel也没有拦截,即有效事件
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;
//14.遍历childview
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.
//15.不可见而且没有正在执行的动画,跳过
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
//16.手指不在该childview范围中,跳过
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
//17.寻找childview对应的TouchTarget
newTouchTarget = getTouchTarget(child);
//18.已经有对应的TouchTarget,比如在同一个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.
//19. newTouchTarget已经有了,跳出for循环
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
//20.复位标志位,避免上次操作带来的影响
resetCancelNextUpFlag(child);
//21.重点:dispatchTransformedTouchEvent方法当child为空时调用自身dispatchTouchEvent
//否则调用child的dispatchTouchEvent方法,在这child不为空,所以将事件分发下去
// 需要注意的是,有可能用户一个手指按在了child1上,另一个手指按在了child2上
// 这样TouchTarget的链就形成了(TouchTarget内部类似单链表)
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();
//22. 如果处理掉了的话,将此child添加到touch链的头部
// 注意这个方法内部会更新 mFirstTouchTarget
newTouchTarget = addTouchTarget(child, idBitsToAssign);
// 23.down或pointer_down事件已经被处理了
alreadyDispatchedToNewTouchTarget = true;
//24.退出循环
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;
}
}
}
// 25.非down事件直接从这里开始处理,不会走上面的一大堆寻找TouchTarget的逻辑
// Dispatch to touch targets.
//26.如果没有找到合适的childview,交给自己处理,调用super.dispatchTouchEvent(event);
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;
//27.上面说了,用户有可能不同的手指按在不同的childview上,所以要遍历TouchTarget的链表
while (target != null) {
final TouchTarget next = target.next;
//28.已经处理过,不再处理
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
//检查是否需要拦截
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
// 如果ViewGroup从半路拦截(cancelChild为true)了touch事件则给touch链上的child发送cancel事件
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
// TouchTarget链中任意一个处理了则设置handled为true
handled = true;
}
// 如果cancel的话,则回收此target节点
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事件时resetTouchState
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;
}
主要的功能,上面注释了一部分。这里总结一下:
ACTION_DOWN
首先,ACTION_DOWN 事件的任务就是找到分发对象(找到接收事件分发的childview)
1.在viewgroup没有被遮罩的情况下,先清空异常及已有状态,给所有之前选择出的Target发送Cancel事件,确保之前Target能收到完整的事件周期; 清除已有Target,复位所有标志位(如PFLAG_CANCEL_NEXT_UP_EVENT、FLAG_DISALLOW_INTERCEPT等) 。
对应编号1-2
2.判断是否需要拦截,某个 view 一旦开始处理事件,如果不消费 ACTION_DOWN 事件,则同一事件序列中的其他事件不会再交给它来处理,直接拦截。如果是ACTION_DOWN 事件,或者向下分发了ACTION_DOWN 事件,则调用onInterceptTouchEvent以确定当前ViewGroup是否拦截该Down事件。与此同时,还要关注禁止拦截属性。禁止拦截由public void requestDisallowInterceptTouchEvent(boolean disallowIntercept)
方法设置,当disallowIntercept为true时,禁止拦截。
对应编号3-8
3.如果事件没有被拦截也没有被cancel,遍历childview寻找合适的分发对象。{如果该childview不可见而且没有正在执行的动画,跳过。如果手指不在该childview范围中,也跳过。找到合适的childview之后,判断是否已经有一个手指按在此childview上(对应编号18),如果是直接跳出循环,因为已经找到了合适的分发对象(即此newTouchTarget.child)。如果否,先复位该childview的状态,然后调用childview的dispatchTouchEvent方法把事件分发下去,并把该childview添加到TouchTarget 链表中,对mFirstTouchTarget赋值(编号3处用到,如果mFirstTouchTarget!=null,说明已经将事件分发下去了)。然后退出循环}(花括号内为循环体)。如果没有合适的childview,则交给自己处理,调用super.dispatchTouchEvent(event);(编号26)
对应编号13-26 。 至此,找到了合适的childview,
非ACTION_DOWN 事件
上面我们得到了TouchTarget,其中的链表记录了接收事件的childview(可能是多个,多点触控)。所以我们先遍历target,检查是否被ViewGroup从半路拦截,如果是,分发cancel,否者正常的把事件分发下去。
图片说明
最后一图以蔽之。