Android Event事件流分析

一、前言:

        最近太忙了,因此好久没空来写博客了,差点让大家以为荒废了。。嘻嘻,这不,今天忙里偷个闲,来写这篇文章,帮助自己,也是帮助大家深入了解Event事件流的整个过程,涉及到的文件有:ViewRoot(Impl),ViewGroup,View,PhoneWindow.DecorView及Activity。这些文件,我会抽空将我的理解写到博客。

二、事件流:

2.1 ViewRoot之InputHandler

        键盘,触屏,摇杆都会产生事件,那么这些事件,是如何传递处理呢?

        首先WMS,即WindowManagerService会:

        1. 接收消息;

        2. 将消息发送到前端进行处理;

        3. 派发消息至ViewRoot;  <== 这里,就是我们真正要开始分析地方

        那ViewRoot是如何接收的呢?别急,马上就讲。

       ViewRoot中,事件接收在InputHandler中完成:

    private final InputHandler mInputHandler = new InputHandler() {
        public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
            startInputEvent(finishedCallback);
            dispatchKey(event, true);
        }

        public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
            startInputEvent(finishedCallback);
            dispatchMotion(event, true);
        }
    };

        而mInputHandler是在SetView中,去注册完成的:

    public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
        synchronized (this) {
            if (mView == null) {
                mView = view;
                ......
                if ((mWindowAttributes.inputFeatures
                        & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
                    mInputChannel = new InputChannel();
                }
                try {
                    mOrigWindowType = mWindowAttributes.type;
                    res = sWindowSession.add(mWindow, mSeq, mWindowAttributes,
                            getHostVisibility(), mAttachInfo.mContentInsets,
                            mInputChannel);
                } catch (RemoteException e) {
                    mAdded = false;
                    mView = null;
                    mAttachInfo.mRootView = null;
                    mInputChannel = null;
                    mFallbackEventHandler.setView(null);
                    unscheduleTraversals();
                    throw new RuntimeException("Adding window failed", e);
                } finally {
                    if (restore) {
                        attrs.restore();
                    }
                }

                ......
				
                if (view instanceof RootViewSurfaceTaker) {
                    mInputQueueCallback =
                        ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
                }
                if (mInputChannel != null) {
                    if (mInputQueueCallback != null) {
                        mInputQueue = new InputQueue(mInputChannel);
                        mInputQueueCallback.onInputQueueCreated(mInputQueue);
                    } else {
                        InputQueue.registerInputChannel(mInputChannel, mInputHandler,
                                Looper.myQueue());
                    }
                }
                ......
            }
        }
    }

        1. 首先初始化一个Channel,mInputChannel;

        2. sWindowSession.add将mInputChannel加入进去;

        注:在ViewRoot内部,有一个IWindowSession的静态成员和一个IWindow的非静态成员:

                 a). IWindowSession负责ViewRoot到WMS的单向请求;

                 b). IWindow则用于WMS回调ViewRoot;

        3. 创建一个输入队列,将Channel和Handler加入(即注册),这样,Event可以通过WMS发送过来。

2.2 ViewRoot之handleMessage

        ViewRoot实际上是继承于Handler,它负责UI所有的事件,如刷新、输入事件,焦点等。因此,ViewRoot重载handleMessage,并处理这些事件。

        在mInputHandler收到handleKey或dispatchMotion后,都会向handler.sendMessage,我们就看看这两个函数发了什么消息:

        键盘按键消息处理,发送一个DISPATCH_KEY消息给handler:

    private void dispatchKey(KeyEvent event, boolean sendDone) {
        //noinspection ConstantConditions
        if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
                if (DBG) Log.d("keydisp", "===================================================");
                if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");

                debug();

                if (DBG) Log.d("keydisp", "===================================================");
            }
        }

        Message msg = obtainMessage(DISPATCH_KEY);
        msg.obj = event;
        msg.arg1 = sendDone ? 1 : 0;

        if (LOCAL_LOGV) Log.v(
            TAG, "sending key " + event + " to " + mView);

        enqueueInputEvent(msg, event.getEventTime());
    }

        DISPATCH_POINTER就是TouchEvent,DISPATCH_TRACKBALL是鼠标的滚轮消息,DISPATCH_GENERIC_MOTION是摇杆消息:

    private void dispatchMotion(MotionEvent event, boolean sendDone) {
        int source = event.getSource();
        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
            dispatchPointer(event, sendDone);
        } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
            dispatchTrackball(event, sendDone);
        } else {
            dispatchGenericMotion(event, sendDone);
        }
    }

    private void dispatchPointer(MotionEvent event, boolean sendDone) {
        Message msg = obtainMessage(DISPATCH_POINTER);
        msg.obj = event;
        msg.arg1 = sendDone ? 1 : 0;
        enqueueInputEvent(msg, event.getEventTime());
    }

    private void dispatchTrackball(MotionEvent event, boolean sendDone) {
        Message msg = obtainMessage(DISPATCH_TRACKBALL);
        msg.obj = event;
        msg.arg1 = sendDone ? 1 : 0;
        enqueueInputEvent(msg, event.getEventTime());
    }

    private void dispatchGenericMotion(MotionEvent event, boolean sendDone) {
        Message msg = obtainMessage(DISPATCH_GENERIC_MOTION);
        msg.obj = event;
        msg.arg1 = sendDone ? 1 : 0;
        enqueueInputEvent(msg, event.getEventTime());
    }

         handleMessage处理很简单,收到后,该调用啥函数就调用啥,不作过多的停留:

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
        ......
        case DISPATCH_KEY:
            deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
            break;
        case DISPATCH_POINTER:
            deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
            break;
        case DISPATCH_TRACKBALL:
            deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
            break;
        case DISPATCH_GENERIC_MOTION:
            deliverGenericMotionEvent((MotionEvent) msg.obj, msg.arg1 != 0);
            break;
         ......
        }
    }

        这几个消息处理都大同小异,因此,本篇以DISPATCH_POINTER(即TouchEvent)为代表吧。

2.3 消息传递及分发:

        2.3.1 deliverPointerEvent

    private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
        if (ViewDebug.DEBUG_LATENCY) {
            mInputEventDeliverTimeNanos = System.nanoTime();
        }

        final boolean isTouchEvent = event.isTouchEvent();
        if (mInputEventConsistencyVerifier != null) {
            if (isTouchEvent) {
                mInputEventConsistencyVerifier.onTouchEvent(event, 0);
            } else {
                mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
            }
        }

        // If there is no view, then the event will not be handled.
        if (mView == null || !mAdded) {
            finishMotionEvent(event, sendDone, false);
            return;
        }

        // Translate the pointer event for compatibility, if needed.
        if (mTranslator != null) {
            mTranslator.translateEventInScreenToAppWindow(event);
        }

        // Enter touch mode on down or scroll.
        final int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
            ensureTouchMode(true);
        }

        // Offset the scroll position.
        if (mCurScrollY != 0) {
            event.offsetLocation(0, mCurScrollY);
        }
        if (MEASURE_LATENCY) {
            lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano());
        }

        // Remember the touch position for possible drag-initiation.
        if (isTouchEvent) {
            mLastTouchPoint.x = event.getRawX();
            mLastTouchPoint.y = event.getRawY();
        }

        // Dispatch touch to view hierarchy.
        boolean handled = mView.dispatchPointerEvent(event);
        if (MEASURE_LATENCY) {
            lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano());
        }
        if (handled) {
            finishMotionEvent(event, sendDone, true);
            return;
        }

        // Pointer event was unhandled.
        finishMotionEvent(event, sendDone, false);
    }

        这里面看似一大堆,实际上,正常的会走到这条语句:

    boolean handled = mView.dispatchPointerEvent(event);

         看到这里,大家还是会纳闷,我平常看到的都是dispatchTouchEvent,别急嘛,接下来就会明朗。

         如果mView.dispatchPointerEvent(event)返回是false,表明没有控件需要,因此,最终将走到finishMotionEvent,同样,返回true也是走到这函数,这函数是啥意思呢?大家不需深入关心,只不过是将这次的消息结果告诉Window而已。

        2.3.2 dispatchPointerEvent (View.java)

    public final boolean dispatchPointerEvent(MotionEvent event) {
        if (event.isTouchEvent()) {
            return dispatchTouchEvent(event);
        } else {
            return dispatchGenericMotionEvent(event);
        }
    }

        我们常看到的dispatchTouchEvent出现了。

        大家注意下,这个方法是final,而我们知道,ViewGroup是继承View的,因此,ViewGroup或但凡继承View的,都不能Override(重写)该方法,但可以继承该方法。

        在ViewRoot中,mView其实就是PhoneWindow.DecorView,而decorView是继承于FrameLayout,FrameLayout继承于ViewGroup,因此,dispatchTouchEvent也就会走到PhoneWindow.DecorView(也重写,并调用super.dispatchTouchEvent)走到ViewGroup中。在ViewGroup中,有重写dispatchTouchEvent方法。

        2.3.3 dispatchTouchEvent(ViewGroup.java)
        这个方法是本篇中的重中之重,大家可看好啦。

    @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 (childrenCount != 0) {
                        // Find a child that can receive the event.
                        // Scan children from front to back.
                        final View[] children = mChildren;
                        final float x = ev.getX(actionIndex);
                        final float y = ev.getY(actionIndex);

                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final View child = children[i];
                            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 = i;
                                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;
    }

        一上来,就遇到个onFilterTouchEventForSecurity方法,接下来,所有的代码,都包函数在其里面,只有它返回true,才会继续执行下去。

    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
        //noinspection RedundantIfStatement
        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
            // Window is obscured, drop this touch.
            return false;
        }
        return true;
    }

        默让是返回true的,这个方法可以继承,可以自己加一些安全策略来决定是否响应TouchEvent,咱们只需知道有这么个方法,可以在以后开发应用中,有需要时,记着有这么个它可以拦截就行。

            // 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();
            }
    /**
     * Cancels and clears all touch targets.
     */
    private void cancelAndClearTouchTargets(MotionEvent event) {
        if (mFirstTouchTarget != null) {
            boolean syntheticEvent = false;
            if (event == null) {
                final long now = SystemClock.uptimeMillis();
                event = MotionEvent.obtain(now, now,
                        MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
                event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
                syntheticEvent = true;
            }

            for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
                resetCancelNextUpFlag(target.child);
                dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits);
            }
            clearTouchTargets();

            if (syntheticEvent) {
                event.recycle();
            }
        }
    }

        如果是DOWN事件,则将之前的Targets和状态都清除,因为上次的应用在运行过程中有可能ANR等导致目前的状态紊乱。

        我们可以看到,在cancelAndClearTouchTargets中,会对上一次保存在TouchTarget中的Child都发送ACTION_CANCEL事件,然后将TouchTarget中的Child全部清除。

什么样的情况会导致Child不在接收后续ACTION,而收到CANCEL?
        Child收到TOUCH ACTION后,开始做自己的事,这时,还用户手未松开,即还是一直是ACTION_MOVE,突然,用户的手一不小心移动到该Child边界外,那么这时,Child是永远不会收到ACTION_UP事件了,那么,Child的状态有可能会乱掉(做滚动视图时,会根据MOVE距离来scrollTo / scrollBy View,然而用户手指移动出界,那么,本该是UP时将View复位或是自动滚动到该停止的地方却没有,界面就乱了。因此,Google Android官方解释为:此时的CANCEL 等同于 UP)。
            // 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;
            }

        这个地方,很重要,为啥?通常,我们在开发时,如果需要根据不同的手势方向,来做不同的效果,如:应用首页支持左、右滑动页,以及首页正文是ListView时,就需要去重写onInterceptTouchEvent(ev)方法(只有ViewGroup才有此方法,View没有):

        如果返回false,本次TouchEvent可以继续往下传递给Child(View / ViewGroup);

        如果返回true,则本次及之后的TouchEvent都不会往下传递,而会将消息发送给当前ViewGroup的onTouchEvent中。

        系统默认该方法返回false。

        if条件判断actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null 只要两者满足其一就行,那么,怎么样才走到else?后续ACTION不为DOWN(即ACTION_MOVE, ACTION_UP, ACTION_CANCEL)且TouchTarget列表为空(函数开始时若是DOWN就清除),就表明当前ViewGroup已经在之前的onInterceptTouchEvent中返回了true,即“我要拦截”。

分情况讨论 intercept

1. 此时ACTION_DOWN,但 TouchTarget列表为空,走if, 且调用当前ViewGroup.onInterceptTouchEvent,如果是true,后续ACTION就走else,下面的代码添加,查找TouchTarget就不会走到,反之,会去找ViewGroup的Child,看看坐标落在谁身上,并添加至TouchTarget中;

2. 若第1步中,返回的是false,那么,此时ACTION_MOVE(正常情况下,点击不算),虽然此时不为ACTION_DOWN,但TouchTarget不为空,所以仍走if, 且调用ViewGroup.onInterceptTouchEvent,此时返回true,那么在之后会将mFirstTouchTarget列表设为NULL,之后的ACTION不会再走if.

            // Check for cancelation.
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

        检查当前是否被设置CANCEL标志,或者当前消息是ACTION_CANCEL

            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;

        这句话的意思是:是否将当前的Event发送给多个Child View(多个Child View可能重叠,因此Pointer是否都给他们),默认是true,即重叠区域的Child View都可以接收。

        如果没有Cancel,也没有设置拦截,则继续往下运行:

                    final int childrenCount = mChildrenCount;
                    if (childrenCount != 0) {
                        // Find a child that can receive the event.
                        // Scan children from front to back.
                        final View[] children = mChildren;
                        final float x = ev.getX(actionIndex);
                        final float y = ev.getY(actionIndex);

                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final View child = children[i];
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                continue;
                            }
							
                            ......
                        }
                    }

        默认final int actionIndex = ev.getActionIndex(); // always 0 for down,然后,开始从最后添加的Child View开始往前遍历,当前ChildView是否可见或当前正在动画,且触摸点[x,y]是否落在ChildView区域中:

    /**
     * Returns true if a child view can receive pointer events.
     * @hide
     */
    private static boolean canViewReceivePointerEvents(View child) {
        return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE
                || child.getAnimation() != null;
    }
    /**
     * Returns true if a child view contains the specified point when transformed
     * into its coordinate space.
     * Child must not be null.
     * @hide
     */
    protected boolean isTransformedTouchPointInView(float x, float y, View child,
            PointF outLocalPoint) {
        float localX = x + mScrollX - child.mLeft;
        float localY = y + mScrollY - child.mTop;
        if (! child.hasIdentityMatrix() && mAttachInfo != null) {
            final float[] localXY = mAttachInfo.mTmpTransformLocation;
            localXY[0] = localX;
            localXY[1] = localY;
            child.getInverseMatrix().mapPoints(localXY);
            localX = localXY[0];
            localY = localXY[1];
        }
        final boolean isInView = child.pointInView(localX, localY);
        if (isInView && outLocalPoint != null) {
            outLocalPoint.set(localX, localY);
        }
        return isInView;
    }

        首先,计算坐标(可能存在滚动条的滚动后的结果),然后判断坐标点是否落在Child中,并返回(true表明点落在Child中);

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

        查找TouchTarget列表,如果能找到,将它与当前的pointerId联系起来(pointerId最多有0 ~ 31个,因此用int来表示位图),如果没找到,则接下来,将该Child加到到TouchTarget列表中:

	if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
		// Child wants to receive touch within its bounds.
		mLastTouchDownTime = ev.getDownTime();
		mLastTouchDownIndex = i;
		mLastTouchDownX = ev.getX();
		mLastTouchDownY = ev.getY();
		newTouchTarget = addTouchTarget(child, idBitsToAssign);
		alreadyDispatchedToNewTouchTarget = true;
		break;
	}

        如果CANCEL,或onInterceptTouchEvent,则直接跳过以上,那么,亲爱的朋友,如果你看的快,应该还没过30秒吧,上面这段代码,到底做了啥?没看懂?OH~MY GOD!好吧,我总结归纳上面的代码:

        如果没有CANCEL且拦截,则我们需要从当前ViewGroup众多的Child中,从最后往前找到一个刚好符合即Visible,坐标点又落上该Child区域的,并将它与pointerId关联起来。(为啥从后往前找? -_-||| 因为,AddView 或 AddChildView总是将当前添加的VIEW显示在最前面,你点击它,当然是想让你看到的VIEW对你产生“物理”反应啦!)。

        继续,手有点累,头有点晕,眼有点花,但无法阻碍我的热情。(我的热情,好像一把火!)

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

        if 就是当 intercept 后执行的,同样会执行到dispatchTransformedTouchEvent,先看else部分,顺带分析 if 情况;

        这里有个while循环遍历整个TouchTarget,如果是新添加的target,则表明已经handle过了。咦,哪里处理过?在上面代码,如果没有CANCEL && 拦截时,有这么一句:

    if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)){...}

        这里的while遍历,也会调用这个函数,这个也基本上是dispatchTouchEvent中最后一个重要的方法了,因为,之后就是对UP做一些重置状态的动作,并返回handled(是否有ChildView响应此次TouchEvent)。

        2.3.4 dispatchTransformedTouchEvent (ViewGroup.java)

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

        看下来,这方法没啥好讲的,如果CANCEL了,Child为空就super.dispatchTouchEvent,否则就child.dispatchTouchEvent;同样,后面的正常流程也是super/child dispatchTouchEvent。

        child如果是ViewGroup,那么继续重复以上过程,如果是view,那么就走View.dispatchTouchEvent。如果child == NULL,则ViewGroup.super.dispatchTouchEvent实际上也是走View.dispatchTouchEvent。

        2.3.5 View.dispatchTouchEvent

    /**
     * Pass the touch screen motion event down to the target view, or this
     * view if it is the target.
     *
     * @param event The motion event to be dispatched.
     * @return True if the event was handled by the view, false otherwise.
     */
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }

        if (onFilterTouchEventForSecurity(event)) {
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                return true;
            }

            if (onTouchEvent(event)) {
                return true;
            }
        }

        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }
        return false;
    }

        如果有注册 OnTouchListener,那么就先将该event 给这个监听,如果该Listener回为true,那么此次event 就算完成;否则,调用View.onTouchEvent,如果是ViewGroup的Child,那就是Child.onTouchEvent,如果之前 intercept ,那么就是当前 ViewGroup 自己的 onTouchEvent。如果最终都没有VIEW处理此次EVENT,则最终返回给ViewRoot,将会丢掉此EVENT。

        至此,整个Event 流程就走了一遍,我想大家也都清楚了吧,若文中写的不对的地方,也请大家指出,欢迎一起讨论!谢谢。

你可能感兴趣的:(Android)