android-----事件分发机制测试系列

Posted 她说巷尾的樱花开了

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android-----事件分发机制测试系列相关的知识,希望对你有一定的参考价值。

        先来说说我遇到的问题,这次测试使用的布局文件是:

<com.hzw.eventtest.MyRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <com.hzw.eventtest.MyLinearLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent">
         <com.hzw.eventtest.MyButton
        	android:id="@+id/mybutton"
        	android:layout_width="wrap_content"
        	android:layout_height="wrap_content"
        	android:text="我的按钮" />
    </com.hzw.eventtest.MyLinearLayout>
</com.hzw.eventtest.MyRelativeLayout>

        也就是说布局图是酱紫的:

                                                      

        具体就是我在MyRelativeLayout中拦截了MOVE事件,在MyLinearLayout中拦截并且消费了DOWN事件,也就是说我仅仅修改了MyRelativeLayout$onInterceptTouchEvent中case条件为MOVE的部分以及MyLinearLayout$onInterceptTouchEvent中case条件为DOWN的部分和MyLinearLayout$onTouchEvent中case条件为DOWN的部分;

        具体测试代码:点击下载

        最后查看Logcat输出:

06-28 09:09:25.237: I/System.out(1643): MainActivity--->dispatchTouchEvent--->ACTION_DOWN
06-28 09:09:25.237: I/System.out(1643): MyRelativeLayout--->dispatchTouchEvent--->ACTION_DOWN
06-28 09:09:25.237: I/System.out(1643): MyRelativeLayout--->onInterceptTouchEvent--->ACTION_DOWN
06-28 09:09:25.237: I/System.out(1643): MyRelativeLayout--->onInterceptTouchEvent--->ACTION_DOWN--->false
06-28 09:09:25.237: I/System.out(1643): MyLinearLayout--->dispatchTouchEvent--->ACTION_DOWN
06-28 09:09:25.237: I/System.out(1643): MyLinearLayout--->onInterceptTouchEvent--->ACTION_DOWN
06-28 09:09:25.237: I/System.out(1643): MyLinearLayout--->onInterceptTouchEvent--->ACTION_DOWN--->true
06-28 09:09:25.246: I/System.out(1643): MyLinearLayout--->onTouchEvent--->ACTION_DOWN
06-28 09:09:25.246: I/System.out(1643): MyLinearLayout--->onTouchEvent--->ACTION_DOWN--->true
06-28 09:09:25.246: I/System.out(1643): MyLinearLayout--->dispatchTouchEvent--->ACTION_DOWN--->true
06-28 09:09:25.246: I/System.out(1643): MyRelativeLayout--->dispatchTouchEvent--->ACTION_DOWN--->true
06-28 09:09:25.246: I/System.out(1643): MainActivity--->dispatchTouchEvent--->ACTION_DOWN--->true
06-28 09:09:25.326: I/System.out(1643): MainActivity--->dispatchTouchEvent--->ACTION_MOVE
06-28 09:09:25.326: I/System.out(1643): MyRelativeLayout--->dispatchTouchEvent--->ACTION_MOVE
06-28 09:09:25.326: I/System.out(1643): MyRelativeLayout--->onInterceptTouchEvent--->ACTION_MOVE
06-28 09:09:25.326: I/System.out(1643): MyRelativeLayout--->onInterceptTouchEvent--->ACTION_MOVE--->true
06-28 09:09:25.326: I/System.out(1643): MyLinearLayout--->dispatchTouchEvent--->ACTION_CANCEL
06-28 09:09:25.326: I/System.out(1643): MyLinearLayout--->dispatchTouchEvent--->ACTION_CANCEL--->false
06-28 09:09:25.326: I/System.out(1643): MyRelativeLayout--->dispatchTouchEvent--->ACTION_MOVE--->false
06-28 09:09:25.326: I/System.out(1643): MainActivity--->onTouchEvent--->ACTION_MOVE
06-28 09:09:25.326: I/System.out(1643): MainActivity--->onTouchEvent--->ACTION_MOVE--->false
06-28 09:09:25.326: I/System.out(1643): MainActivity--->dispatchTouchEvent--->ACTION_MOVE--->false
06-28 09:09:25.336: I/System.out(1643): MainActivity--->dispatchTouchEvent--->ACTION_MOVE
06-28 09:09:25.336: I/System.out(1643): MyRelativeLayout--->dispatchTouchEvent--->ACTION_MOVE
06-28 09:09:25.336: I/System.out(1643): MyRelativeLayout--->onTouchEvent--->ACTION_MOVE
06-28 09:09:25.336: I/System.out(1643): MyRelativeLayout--->onTouchEvent--->ACTION_MOVE--->false
06-28 09:09:25.336: I/System.out(1643): MyRelativeLayout--->dispatchTouchEvent--->ACTION_MOVE--->false
06-28 09:09:25.336: I/System.out(1643): MainActivity--->onTouchEvent--->ACTION_MOVE
06-28 09:09:25.336: I/System.out(1643): MainActivity--->onTouchEvent--->ACTION_MOVE--->false
06-28 09:09:25.336: I/System.out(1643): MainActivity--->dispatchTouchEvent--->ACTION_MOVE--->false
06-28 09:09:25.412: I/System.out(1643): MainActivity--->dispatchTouchEvent--->ACTION_UP
06-28 09:09:25.416: I/System.out(1643): MyRelativeLayout--->dispatchTouchEvent--->ACTION_UP
06-28 09:09:25.416: I/System.out(1643): MyRelativeLayout--->onTouchEvent--->ACTION_UP
06-28 09:09:25.416: I/System.out(1643): MyRelativeLayout--->onTouchEvent--->ACTION_UP--->false
06-28 09:09:25.416: I/System.out(1643): MyRelativeLayout--->dispatchTouchEvent--->ACTION_UP--->false
06-28 09:09:25.416: I/System.out(1643): MainActivity--->onTouchEvent--->ACTION_UP
06-28 09:09:25.416: I/System.out(1643): MainActivity--->onTouchEvent--->ACTION_UP--->false
06-28 09:09:25.416: I/System.out(1643): MainActivity--->dispatchTouchEvent--->ACTION_UP--->false

        下面我们来分析下具体的输出过程

        为了便于分析,先来贴出此测试过程中用到的部分源码:

        ViewGroup$dispatchTouchEvent

 @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }

        boolean handled = false;
        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.
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }

            // Check for interception.
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                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;
            }

            // 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) {
                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 View[] children = mChildren;

                        final boolean customOrder = isChildrenDrawingOrderEnabled();
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = customOrder ?
                                    getChildDrawingOrder(childrenCount, i) : i;
                            final View child = children[childIndex];
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                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);
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                // Child wants to receive touch within its bounds.
                                mLastTouchDownTime = ev.getDownTime();
                                mLastTouchDownIndex = childIndex;
                                mLastTouchDownX = ev.getX();
                                mLastTouchDownY = ev.getY();
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }
                        }
                    }

                    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.
            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;
    }
        ViewGroup$dispatchTransformedTouchEvent

 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.
        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;
    }

        具体分析过程:

        注意:分发顺序是:Activity----->ViewGroup----->View

                    消费顺序是:View------>ViewGroup----->Activity

                    View中的事件方法执行流程是:dispatchTouchEvent----->onTouchEvent

                    ViewGroup中的事件方法执行流程是:dispatchTouchEvent----->onInterceptTouchEvent----->onTouchEvent

        (1)先来看DOWN事件部分:

            事件首先传递到MainActivity,调用它的dispatchTouchEvent分发到他的子View(MyRelativeLayout上),因为是DOWN事件,满足ViewGroup$dispatchTouchEvent源码的第23行if语句的第一个条件,进入if语句块中,因为我们并没有调用requestDisallowInterceptTouchEvent来干预事件的分发过程,所以会执行第27行的onInterceptTouchEvent方法,我们的测试中MyRelativeLayout没有拦截DOWN事件,因而该方法默认返回值是false赋给intercepted,所以你有了Logcat第4行的输出,接着执行第46行,满足if语句条件,进入if语句块中,这个里面比较关键的代码是第85行的dispatchTransformedTouchEvent方法,这个方法会递归的处理当前View的子View,所以你会发现Logcat第11行MyRelativeLayout的dispatchTouchEvent方法才算真正结束,这里只需要知道第91行会调用addTouchTarget方法,该方法会在其子View的分发事件(dispatchTouchEvent)返回true的情况下执行,在它里面会给mFirstTouchTarget赋值即可,因为MyRelativeLayout子View是MyLinearLayout,所以执行MyLinearLayout的dispatchTouchEvent方法,接着执行MyLinearLayoutonInterceptTouchEvent方法,因为MyLinearLayout拦截了DOWN事件,因而onInterceptTouchEvent返回true,那么这时候ViewGroup$dispatchTouchEvent的第46---108行代码将不再执行,因为此时mFirstTouchTarget还是null的,所以会执行第111行的if语句块,调用dispatchTransformedTouchEvent方法,传入的第三个参数是null,查看ViewGroup$dispatchTransformedTouchEvent源码的第11行,发现他会执行super的dispatchTouchEvent方法,因为我们没有为MyLinearLayout设置onTouch监听事件,所以他直接执行了onTouchEvent方法,并且我们消费了这个DOWN事件,所以有了Logcat第9行的输出,接下来就是递归返回过程了,即Logcat第10--12行的输出部分;

        (2)接下来分析第一次MOVE事件

            和上面一样,事件首先到了MainActivity,调用他的dispatchTouchEvent方法进行分发,接着事件分发到了MyRelativeLayout上面,调用他的dispatchTouchEvent方法,因为第一次DOWN事件中,我们已经将mFirstTouchTarget的值设置为非null,所以ViewGroup$dispatchTouchEvent方法走到第23行的时候仍然满足if判断条件,执行第27行的onInterceptTouchEvent方法,所以有了第15行的Logcat输出,因为我们在MyRelativeLayout中拦截了MOVE事件,所以intercepted的值将会被赋值为true,因而ViewGroup$dispatchTouchEvent的第46--108行的代码将不会执行,到了第111行判断mFirstTouchTarget不为null,执行else语句部分,这里比较关键的在于第125行,因为此时的intercepted值为true,所以cancelChild值将为true,在执行第127行dispatchTransformedTouchEvent的时候将cancelChild值传入,查看ViewGroup$dispatchTransformedTouchEvent的源码第9行,你会发现他执行了ACTION_CANCEL,所以出现了我们Logcat输出的第17/18行,因而第127行的if条件内容将为false,所以handled的值此时仍然是false,因为cancelChild值是true,所以执行第131行,并且此时的predecessor等于null,因而修改mFirstTouchTarget的值为next,这里就比较重要了,此处的next是null,为什么呢?因为之前mFirstTouchTarget的值是MyLinearLayout,虽然MyLinearLayout有子View(MyButton),但是MyLinearLayout把DOWN时间消费了,所以MyButton根本就没有加入到事件处理的链表中,所以对mFirstTouchTarget的值进行了修改,ViewGroup$dispatchTouchEvent的第148--161行不再会修改handled的值,那么我们可以认为MyRelativeLayout的dispatchTouchEvent方法执行结束,因为此时事件还没有被消费,那么只能由MainActivity来进行处理了,所以有了Logcat第20--22行的输出;

        (3)接下来分析第二次以后的MOVE事件

           同样事件首先由MainActivity的dispatchTouchEvent分发到MyRelativeLayout上,执行他的dispatchTouchEvent方法,这时候判断ViewGroup$dispatchTouchEvent第23行的if语句部分,发现部门组条件,那么会执行第35行的else语句部分,设置intercepted的值为true,同样的不会执行第46--108行部分,在判断第111行的mFirstTouchTarget是否为null时,满足条件,执行dispatchTransformedTouchEvent方法,传入的第3个参数是null,那么会执行super的dispatchTouchEvent方法,这属于View的事件分发过程,同样我们没有为MyRelativeLayout设置onTouch方法,所以他会直接执行onTouchEvent方法,所以有了Logcat第25行的输出,接下来在onTouchEvent执行结束之后返回false,因为我们没有在MyRelativeLayout中消费MOVE事件,因为该事件没有处理完,因而会回传给MainActivity来进行处理;

        (4)接下来就是UP事件了:

           UP事件的分析和第二次以后的MOVE事件过程一致,就不再赘述了;

        从上面的分析中,我们可以得出结论:

        某一个View一旦决定拦截,那么这个事件序列以后的部分只能由他来处理,前提条件是以后的事件是可以到达该View的,就像上面的例子,DOWN事件是由MyLinearLayout来拦截消费的,但是MOVE事件却不是他处理的,原因在于MyRelativeLayout对MOVE事件进行了拦截,事件根本就不会到达MyLinearLayout;





以上是关于android-----事件分发机制测试系列的主要内容,如果未能解决你的问题,请参考以下文章

android-----事件分发机制测试系列

Android系列View的事件分发机制

Android View 事件分发机制

“framework必会”系列:Android Input系统事件分发机制

Android 事件分发事件分发源码分析 ( ViewGroup 事件传递机制 四 | View 事件传递机制 )

Android事件分发机制五:面试官你坐啊