乐趣区

关于android: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<View> 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,防止它们的指标变得不同步。

退出移动版