Android事件分發機制源碼分析

前面寫過一篇文章,說了下事件分發機制的方法和大致流程,本文嘗試從源碼的角度一層一層的看下分發機制。

源碼的查看:https://www.androidos.net.cn/sourcecode(可能是我下的源碼有問題,部分方法我是在線查看的)

Activity的事件分發機制

我們從activity的dispatchTouchEvent方法進行源碼分析:

    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

點進去看到,onUserInteraction是個空方法,這裏是用來實現屏保功能的,當activity位於棧頂時,觸屏點擊home、menu、back會觸發。

    public void onUserInteraction() {
    }

然後我們來看第二個判斷

 if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }

繼續往下看,

    public abstract boolean superDispatchTouchEvent(MotionEvent event);

這玩意是個抽象方法,對應的Window也是個抽象類,我們能找到PhoneWindow,

    @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);
    }

然後我們在看下這個mDecor是啥,

找到這個類

public class DecorView extends FrameLayout implements RootViewSurfaceTaker, WindowCallbacks

他是繼承FrameLayout的,也就是mDecor.SuperDispatchTouchEvent即等同於Viegroup的分發機制。(即事件從activity傳遞到了viewgroup)

再看最後一個onTouch方法,

    public boolean onTouchEvent(MotionEvent event) {
        if (mWindow.shouldCloseOnTouch(this, event)) {
            finish();
            return true;
        }

        return false;
    }

這裏默認返回false,就是不處理,向下層分發,那我們來看下這個判斷裏面。

    public boolean shouldCloseOnTouch(Context context, MotionEvent event) {
        final boolean isOutside =
                event.getAction() == MotionEvent.ACTION_DOWN && isOutOfBounds(context, event)
                || event.getAction() == MotionEvent.ACTION_OUTSIDE;
        if (mCloseOnTouchOutside && peekDecorView() != null && isOutside) {
            return true;
        }
        return false;
    }

這裏主要判斷是否在邊界外,在即消費事件,返回true,分發結束,反之返回false,activity層的分發也結束,扔給viewgroup繼續分發,直到被消費。

viewgroup的分發機制

我們從ViewGroup的dispatchTouchEvent方法進行源碼分析:

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

                    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 ArrayList<View> preorderedList = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = getAndVerifyPreorderedIndex(
                                    childrenCount, i, customOrder);
                            final View child = getAndVerifyPreorderedView(
                                    preorderedList, children, childIndex);

代碼很長,挑一點看看(不完整,感興趣的自己查看),就是判斷事件沒有取消也沒有被攔截,然後給viewgroup內的子view進行遍歷,繼續看重點

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

我們給這個dispatchTransformedTouchEvent點進去,

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

這裏面進行了判斷,事件傳遞給了view(即child)進行分發,或者給他的上一層viewgroup進行分發,直到事件分發結束,即被消費。

回過頭來,我們看攔截的判斷

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

這裏面的事件被攔截即 mFirsTouchTarget!=null不成立,即不攔截,mFirsTouchTarget!=null,disallowIntercept表示是否允許被攔截,是可以用代碼來控制的,經過判斷,允許被攔截再調用攔截的方法,

    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
                && ev.getAction() == MotionEvent.ACTION_DOWN
                && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
                && isOnScrollbarThumb(ev.getX(), ev.getY())) {
            return true;
        }
        return false;
    }

這裏面進行多個判斷,默認返回false,即不攔截。攔截的要求大致上,這個事件是來自使用者的輸入、是down事件、這個是按鈕、點擊的事件只在viewgroup內。一旦攔截了,它就會向它的父類分發,也就是view的分發,但執行ViewGroup的onTouch() ->> onTouchEvent() ->> performClick() ->> onClick(),即自己處理該事件,事件不會往下傳遞(具體請參考View事件的分發機制中的View.dispatchTouchEvent())。(可以理解爲雖然是個viewgroup,但裏面並沒有子view,所以事件分發相當於view的事件分發),這個地方要注意。

View的事件分發機制

我們從View的dispatchTouchEvent方法進行源碼分析:(源碼可能下的有點問題,我們在線看下)

 boolean result = false;

        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }

        final int actionMasked = event.getActionMasked();
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // Defensive cleanup for new gesture
            stopNestedScroll();
        }

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

            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }

它返回的是result,即決定是否繼續分發,返回true,即事件被消費,false即要調用onTouch方法。返回true有三種情況

1. view是可點擊的且handleScrollBarDragging

   看下源碼(太長,看下什麼時候返回true)

 * @return true if the event was handled as a scroll bar dragging, false otherwise.
     */
    protected boolean handleScrollBarDragging(MotionEvent event) {

翻譯:如果作爲一個滾動條拖動事件處理返回true

2. view可點擊且onTouch事件不爲空

3. onTouch事件返回true

下面看下onTouchEvent方法

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

即view可點擊進入switch判斷具體DOWN、UP等事件,重點看下這個

    public boolean performClick() {
        final boolean result;
        final ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnClickListener != null) {
            playSoundEffect(SoundEffectConstants.CLICK);
            li.mOnClickListener.onClick(this);
            result = true;
        } else {
            result = false;
        }

        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);

        notifyEnterOrExitForAutoFillIfNeeded(true);

        return result;
    }

根據代碼我們知道只要我們通過setOnClickListener()爲控件View註冊1個點擊事件,那麼就會給mOnClickListener變量賦值(即不爲空),則會往下回調onClick() & performClick()返回true。即調用onTouch事件要調用performClick事件,當這些執行完才能執行我們常見的onClick事件,至此,事件分發結束。

核心結論

事件逐層分發,判斷是否攔截,攔截就本層消費,否則向下分發,直至被消費。

寫在最後

宣傳一下自己的技術交流羣:589780530

裏面有妹子 裏面有妹子 裏面有妹子 重要的事情說三遍,另外還有Go/C/python等其他領域的大佬,歡迎加入

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章