安卓事件分发机制源码详读

深入理解事件分发对解决事件冲突上有着很是大的帮助,安卓事件分发机制也是须要重点掌握。不少效果实现都必须配合手势来实现。涉及手势必然会有事件,事件的分发和消费都应该十分清楚。bash

首先咱们能够想象一下,咱们手指点击的地方是 Activity,根据以前的一篇文章讲过,setContentView 设置的布局文件,最终是由 PhoneWindow 内部维护的 DecorView 来进行加载工做的。因此咱们能看到的 view 必然是在 Activity 中,那是否是点击的事件必然也是从 Activity 中开始分发的? 分发事件翻译成英文的大概意思就是 dispatchEvent。 那么直接到 Activity 中去查找是否有类似名称的方法,找到了一个 dispatchTouchEvent 方法,这个方法就是咱们要找的。 代码以下:app

/**
     * Called to process touch screen events.  You can override this to
     * intercept all touch screen events before they are dispatched to the
     * window.  Be sure to call this implementation for touch screen events
     * that should be handled normally.
     *
     * @param ev The touch screen event.
     *
     * @return boolean Return true if this event was consumed.
     */
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // 检查手势按下
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 其余的一些事件,好比悬浮球、屏幕熄屏幕点亮事件处理.
            onUserInteraction();
        }
        //  交给 PhoneWindow 的 superDispatchTouchEvent
       // 至于为何是 PhonwWindow, 请看个人布局文件加载过程分析文章. 
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }

  //  若是全部的视图都没有处理事件,事件回传给  Activity 的 onTouchEvent
        return onTouchEvent(ev);
    }
复制代码

这里我将它的英文注释也给出,根据注释知道,若是重载这个方法返回 true 的话,全部的事件都不会传递下去。ide

上面的方法最终会到 ViewGroup 中, 为何呢?请阅读个人布局加载文件分析文章。请看 ViewGroup 的 dispatchTouchEvent 方法以下:源码分析

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        .... 省略部分代码

        boolean handled = false;
        // 有效的手势按下会返回 true, 即当前窗口是否是被遮挡住
        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.
                // 新的事件产生,清空老的事件产生的数据,响应新的事件
               //  首先重置 MotionEvent,其次是将维护 TouchTarget 的链表清空
                cancelAndClearTouchTargets(ev);

               // 将 mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
                resetTouchState();
            }

            // Check for interception.
            final boolean intercepted;
            // 已经肯定了点击的 view 后,这个值 mFirstTouchTarget 不为空。
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                   // 若是是 down 事件,这个返回值必定为 false, 由于前面调用了 resetTouchState() 方法
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    // 若是是 ViewGroup 的子类,能够重写此方法来拦截事件。返回 true 拦截。
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    // 若是不是 down 事件且  mFirstTouchTarget 不为空
                    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;
            }

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

             // 事件未被 ViewGroup 拦截,子 view 有机会处理事件
            if (!canceled && !intercepted) {

                // If the event is targeting accessibility 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);
                  
                    // 当前 ViewGroup 的子 view 个数.
                    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.

                        // 这个方法对 view 响应事件的顺序进行调整,根据 z 轴的值,这也很好理解
                        //  z 轴的值越大,说明  view 处于最顶层,应当优先处理事件.
                        final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();

                        // 当前 ViewGroup 的子 view 
                        final View[] children = mChildren;
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = getAndVerifyPreorderedIndex(
                                    childrenCount, i, customOrder);

                             // 取出 view.
                            final View child = getAndVerifyPreorderedView(
                                    preorderedList, children, childIndex);

                            ..... 省略部分代码

                            // 这里的第一个方法是判断,当前的 view 是否有动画正在执行,是否可见
                            // 第二个方法检查当前按下的点是否在 view 上, 若是没在就跳过。
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }

                            // 第一个事件来的时候,newTouchTarget 为空。可是若是按下后移动或其余手指按下 newTouchTarget 不为空 ,就会跳过循环。
                            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);
                            // 这个方法很是关键,将事件向下分发的地方。若是是 view 则调用
                            // View 的dispatchTouchEvent, 若是是 ViewGroup 则又递归查找当前 ViewGroup 下的全部 view
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                    ..... 省略部分代码
                                // 事件一旦被某个 view 消费,这里就会将这个 view 存放到链表的头节点,为了让后续的全部事件都交给它来处理
                                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(); } ..... 省略部分代码 } } // Dispatch to touch targets. // 若是没有 view 消费,最终会调用自己的 onTouchEvent 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; // 若是是新的事件被处理,返回 true。说明有事件已经被 view 消费啦 if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) { handled = true; } else { // 当前的 view 是否设置了抬起标示,若是设置了,说明当前的 view 事件即将结束。 final boolean cancelChild = resetCancelNextUpFlag(target.child) || intercepted; // 将后续事件分发到 cancelChild if (dispatchTransformedTouchEvent(ev, cancelChild, target.child, target.pointerIdBits)) { handled = true; } // 当前的 child 事件处理结束,将其回收 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); } // 若是 handled 为 true, 就会回到最终 Activity 的 dispatchTouchEvent , 条件判断不成立,而执行 Activity onTouchEvent 方法。 return handled; } 复制代码

关键代码都有注释,再次梳理一下流程,首先 ACTION_DOWN 事件发生,会先重置 TouchTargets,重置 mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT; 接着当前容器是否重载 onInterceptTouchEvent 方法并返回 true, 若是返回 false 倒序遍历该容器下的全部子 view, 咱们在布局中写的控件,通常状况下后面的显示在最上面,除非设置了 z 轴方向的值,这个方法 buildTouchDispatchChildList() 就是将 z 轴越到的进行排序。而后取出一个子 view 并判断它是否可见,是否执行动画,以及是否被点击到。就会进入最为关键的方法 dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,View child, int desiredPointerIdBits), 这个方法内部根据传入进来的 child 是否为空,将事件由自己的 dispatchTouchEvent, 仍是父容器的 dispatchTouchEvent。若是 child 消费了事件返回 true, mFirstTouchTarget 就会指向当前 child 的 target。接着就能够继续响应后续的事件。布局

OK,上面分析了 ViewGroup 代码中一长串的代码,接下里就是看 view 的 dispatchTouchEvent 作了什么。post

public boolean dispatchTouchEvent(MotionEvent event) {
        ...... 省略部分代码

        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //noinspection SimplifiableIfStatement
            // 咱们平时给 view 设置的 setOnClickListener 就是经过它来维护的。
            // li.mOnTouchListener.onTouch(this, event) 这个比较关键啦,若是咱们给 view setOnTouchListener 而且返回了 true, 那么 onTouchEvent 就不被调用
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
            
            // 若是上面为 true,onTouchEvent 不被调用
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }

        ...... 省略部分代码
        return result;
    }

复制代码

来看 onTouchEvent,咱们只找咱们关心的点击事件,长按事件。动画

public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();
        
        // view 是否能够点击。
        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                setPressed(false);
            }
            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them. return clickable; } if (mTouchDelegate != null) { if (mTouchDelegate.onTouchEvent(event)) { return true; } } if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) { switch (action) { case MotionEvent.ACTION_UP: mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; if ((viewFlags & TOOLTIP) == TOOLTIP) { handleTooltipUp(); } if (!clickable) { removeTapCallback(); removeLongPressCallback(); mInContextButtonPress = false; mHasPerformedLongPress = false; mIgnoreNextUpEvent = false; break; } boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { // take focus if we don't have it already and we should in
                        // touch mode.
                        boolean focusTaken = false;
                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                            focusTaken = requestFocus();
                        }

                        if (prepressed) {
                            // The button is being released before we actually
                            // showed it as pressed.  Make it show the pressed
                            // state now (before scheduling the click) to ensure
                            // the user sees it.
                            setPressed(true, x, y);
                        }
                        
                       // 由于点击事件和长按事件只是经过按下的事件来区分的,若是 mHasPerformedLongPress 为 true 表示长按发生
                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                            // This is a tap, so remove the longpress check
                            removeLongPressCallback();

                            // Only perform take click actions if we were in the pressed state
                            if (!focusTaken) {
                                // Use a Runnable and post this rather than calling
                                // performClick directly. This lets other visual state
                                // of the view update before click actions start.
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                //调用 performClickInternal 方法,内部调用设置的点击监听器 li.mOnClickListener.onClick(this);
                                if (!post(mPerformClick)) {
                                    performClickInternal();
                                }
                            }
                        }

                        if (mUnsetPressedState == null) {
                            mUnsetPressedState = new UnsetPressedState();
                        }

                        if (prepressed) {
                            postDelayed(mUnsetPressedState,
                                    ViewConfiguration.getPressedStateDuration());
                        } else if (!post(mUnsetPressedState)) {
                            // If the post failed, unpress right now
                            mUnsetPressedState.run();
                        }

                        removeTapCallback();
                    }
                    mIgnoreNextUpEvent = false;
                    break;

                case MotionEvent.ACTION_DOWN:
                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
                    }
                    mHasPerformedLongPress = false;

                    if (!clickable) {
                        checkForLongClick(0, x, y);
                        break;
                    }

                    if (performButtonActionOnTouchDown(event)) {
                        break;
                    }

                    // Walk up the hierarchy to determine if we're inside a scrolling container. boolean isInScrollingContainer = isInScrollingContainer(); // For views inside a scrolling container, delay the pressed feedback for // a short period in case this is a scroll. if (isInScrollingContainer) { mPrivateFlags |= PFLAG_PREPRESSED; if (mPendingCheckForTap == null) { mPendingCheckForTap = new CheckForTap(); } mPendingCheckForTap.x = event.getX(); mPendingCheckForTap.y = event.getY(); postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); } else { // Not inside a scrolling container, so show the feedback right away setPressed(true, x, y); // 检查长按事件,若是事件大于 500 毫秒就会触发 performLongClick, 内部调用了performLongClickInternal,而后调用 li.mOnLongClickListener.onLongClick(View.this) checkForLongClick(0, x, y); } break; case MotionEvent.ACTION_CANCEL: ...... case MotionEvent.ACTION_MOVE: ........ } return true; } return false; } 复制代码

再次梳理 View 的 dispatchTouchEvent , 首先检查 View 是否设置 setOnTouchListener 并返回 true。 若是没有设置则调用 View 的 onTouchEvent。 在这个方法里处理 view 点击和长按处理。ui

说明一个顺序: View 的setOnTouchListener > onTouchEvent, 长按事件 > 点击事件。this

最后来一张流程分析图结束源码分析的过程。 spa

事件分发源码分析.jpeg
相关文章
相关标签/搜索