Android中ViewGroup的dispatchTouchEvent方法源码分析(一)

【Android中ViewGroup的dispatchTouchEvent方法源码分析(一)】ps:本文系为转载文章,阅读原文可读性会更好,文章末尾有原文链接
ps:源码是基于 android api 27 来分析的
前面写了好几篇 View 事件的分发,但更多的偏向于总结结论并写 demo 来演示验证结论;这一篇我们来详细的分析 View 事件分发中的 ViewGroup 中的 dispatchTouchEvent 方法源码。
首先我们先找到 View 事件分发的源头,那就是 Activity 中的 dispatchTouchEvent方法:
public boolean dispatchTouchEvent(MotionEvent ev) {

//1、 if (ev.getAction() == MotionEvent.ACTION_DOWN) { onUserInteraction(); }//2、 if (getWindow().superDispatchTouchEvent(ev)) { return true; }//3、 return onTouchEvent(ev);

}
注释1 是 down 事件,onUserInteraction 是空的方法,不必理会,注释2 如果 if 语句的值是 false,那么就执行注释3 的返回语句,也就是 Activity 的 onTouchEvent 方法,即 Activity 处理触摸事件;那么注释2 是什么呢?注释2 是事件的分发,它首先分发给 Window,getWindow 方法就是获取一个 Window,Window 的实现类是 PhoneWindow,所以我们看看 PhoneWindow 的 superDispatchTouchEvent 方法;
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
//4、 return mDecor.superDispatchTouchEvent(event);

}
看注释4,mDecor 是一个 DecorView 类对象,父类是 FrameLayout,FrameLayout 继承于 ViewGroup;DecorView 是我们经常用到 setContentView 方法时的底层根布局,我们往下查看 DecorView 的 superDispatchTouchEvent 方法;
public boolean superDispatchTouchEvent(MotionEvent event) {
//5、 return super.dispatchTouchEvent(event);

}
我们看注释5,最终调用了父类的 dispatchTouchEvent 方法,这时候终于见到我们的主角 ViewGroup 了,ViewGroup 的 dispatchTouchEvent 方法如下所示:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//6、 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); }//7、 boolean handled = false; //8、 if (onFilterTouchEventForSecurity(ev)) { final int action = ev.getAction(); //9、 final int actionMasked = action & MotionEvent.ACTION_MASK; //10、 // 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(); }//11、 // Check for interception. final boolean intercepted; //12、 if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) {//13、 final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0; if (!disallowIntercept) {//14、 intercepted = onInterceptTouchEvent(ev); //15、 ev.setAction(action); // restore action in case it was changed } else { intercepted = false; }//16、 } 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); }//17、 // Check for cancelation. final boolean canceled = resetCancelNextUpFlag(this) || actionMasked == MotionEvent.ACTION_CANCEL; //18、 // Update list of touch targets for pointer down, if needed. final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0; //19、 TouchTarget newTouchTarget = null; //20、 boolean alreadyDispatchedToNewTouchTarget = false; //21、 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; //21A、 if (actionMasked == MotionEvent.ACTION_DOWN || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN) || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {//22、 final int actionIndex = ev.getActionIndex(); // always 0 for down//23、 final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex) : TouchTarget.ALL_POINTER_IDS; //24、 // Clean up earlier touch targets for this pointer id in case they // have become out of sync. removePointersFromTouchTargets(idBitsToAssign); final int childrenCount = mChildrenCount; //25、 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(); //26、 final boolean customOrder = preorderedList == null && isChildrenDrawingOrderEnabled(); //27、 final View[] children = mChildren; for (int i = childrenCount - 1; i >= 0; i--) {//28、 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; }//29、 if (!canViewReceivePointerEvents(child) || !isTransformedTouchPointInView(x, y, child, null)) { ev.setTargetAccessibilityFocus(false); continue; }//30、 newTouchTarget = getTouchTarget(child); //31、 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; }//32、 resetCancelNextUpFlag(child); //33、 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(); }//34、 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; } } }//35、 // Dispatch to touch targets. if (mFirstTouchTarget == null) {//36、 // No touch targets so treat this as an ordinary view. handled = dispatchTransformedTouchEvent(ev, canceled, null, TouchTarget.ALL_POINTER_IDS); //37、 } else {//38、 // 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 {//39、 final boolean cancelChild = resetCancelNextUpFlag(target.child) || intercepted; //40、 if (dispatchTransformedTouchEvent(ev, cancelChild, target.child, target.pointerIdBits)) { handled = true; }//41、 if (cancelChild) {//42、 if (predecessor == null) { mFirstTouchTarget = next; //43、 } else { predecessor.next = next; } target.recycle(); target = next; continue; } }//44、 predecessor = target; target = next; } }//45、 // Update list of touch targets for pointer up or cancel, if needed. if (canceled || actionMasked == MotionEvent.ACTION_UP || actionMasked == MotionEvent.ACTION_HOVER_MOVE) { resetTouchState(); //46、 } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) { final int actionIndex = ev.getActionIndex(); final int idBitsToRemove = 1 << ev.getPointerId(actionIndex); removePointersFromTouchTargets(idBitsToRemove); } }//47、 if (!handled && mInputEventConsistencyVerifier != null) { mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1); } return handled;

}
为了方便阅读,我们把代码一段一段的拿出来分析,有些不重要的代码我会进行省略。
//6、 if (mInputEventConsistencyVerifier != null) { mInputEventConsistencyVerifier.onTouchEvent(ev, 1); } ...... //7、 boolean handled = false;

注释6 它表示的是验证事件是否连续;注释7 表示的是这个变量用来记录这个事件是否被处理过。
//8、 if (onFilterTouchEventForSecurity(ev)) { ...... }

注释8 这里是为了过滤掉一些不合理的事件,比如说当前的 View 的窗口被遮挡了,比如再详细一点弹出一个 Dialog;如果没有被挡住,那么就执行 if 括号里面的语句。
//9、 final int actionMasked = action & MotionEvent.ACTION_MASK; //10、 // 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(); }

注释9 表示重置前面为0 ,只留下后八位,用于判断相等时候,可以提高性能;注释10 表示判断是不是 down 事件,如果是的话,就要做初始化操作,cancelAndClearTouchTargets 方法会调用 resetCancelNextUpFlag 方法,而 resetCancelNextUpFlag 方法是为了清空 mPrivateFlags 的 PFLAG_CANCEL_NEXT_UP_EVEN 标记,作用是将下一个事件变成 Cancel;resetTouchState 方法清空了 mGroupFlags 的 FLAG_DISALLOW_INTERCEPT 标记,如果设置了FLAG_DISALLOW_INTERCEPT,ViewGroup 对触摸事件进行拦截;resetTouchState 方法调用了 clearTouchTargets 方法,目的是为了清空 mFirstTouchTarget 链表,并设置 mFirstTouchTarget 为 null,mFirstTouchTarget 是"接受触摸事件的 View "所组成的单链表。
//11、 // Check for interception. final boolean intercepted; //12、 if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) {//13、 final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0; if (!disallowIntercept) {//14、 intercepted = onInterceptTouchEvent(ev); //15、 ev.setAction(action); // restore action in case it was changed } else { intercepted = false; }//16、 } else { // There are no touch targets and this action is not an initial down // so this view group continues to intercept touches. intercepted = true; }

注释11 表示检查是否拦截;注释12 表示如果为 down 事件,或者 mFirstTouchTarget 不为null(那么事件直接给到自己),先不拦截;注释13 表示查看是否设置了禁止拦截的标记,即子元素是否调用了 getParent().requestDisallowInterceptTouchEvent(true) 语句;注释14 表示 ViewGroup 的 onInterceptTouchEvent 方法是否要拦截事件,它默认不执行拦截,除非它的子类(注意是子类不是子元素)重写它的 onInterceptTouchEvent 方法并返回 true;注释15 表示重新恢复 Action,以免 Action 在上面的步骤被改变了;注释16 表示事件已经初始化过了,而且没有子 View 被分配处理,这就说明了 ViewGroup 已经拦截了过这个事件了,那么 ViewGroup 第二次就不会是否需要拦截了的。
//17、 // Check for cancelation. final boolean canceled = resetCancelNextUpFlag(this) || actionMasked == MotionEvent.ACTION_CANCEL; //18、 // Update list of touch targets for pointer down, if needed. final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0; //19、 TouchTarget newTouchTarget = null; //20、 boolean alreadyDispatchedToNewTouchTarget = false;

注释17 表示查看 viewFlag 是否被标记了 PFLAG_CANCEL_NEXT_UP_EVENT,那么下一步应该是 Cancel 事件,或者假设当前的 Action 为取消,那么当前事件就是取消了;注释18 表示当前的 ViewGroup 是不是支持把 MotionEvent 传送到不同的 View 当中,比如我们把两个手指放到了屏幕上,是否要将第二个手指的事件传送下面去;注释19 表示新的触摸对象;注释20 表示是否把事件分配给了新的触摸。
//21、 if (!canceled && !intercepted) {//21A、 if (actionMasked == MotionEvent.ACTION_DOWN || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN) || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {//22、 final int actionIndex = ev.getActionIndex(); // always 0 for down//23、 final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex) : TouchTarget.ALL_POINTER_IDS; //24、 // Clean up earlier touch targets for this pointer id in case they // have become out of sync. removePointersFromTouchTargets(idBitsToAssign); ...... } }

注释21 表示如果事件不是取消事件,也没有进行拦截;注释21A 表示如果是个新的 down 事件,或者是有新的触摸点,又或者是光标来回移动事件;注释22 表示这个事件的索引,即第几个事件,如果是 up 事件就是1;注释23 表示获取分配的 id 的 bit 数量;注释24 表示清除 Targets 中相应的 pointer 中的 ids,避免它们的目标变得不同步。

    推荐阅读