安卓事件分發機制源碼詳讀

深入理解事件分發對解決事件衝突上有着很是大的幫助,安卓事件分發機制也是須要重點掌握。不少效果實現都必須配合手勢來實現。涉及手勢必然會有事件,事件的分發和消費都應該十分清楚。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
相關文章
相關標籤/搜索