Android事件機(jī)制源碼理解

Android的事件分發(fā)機(jī)制是一個很重要的知識點(diǎn),也是基礎(chǔ)知識里相對比較難的一個知識點(diǎn),但是其用途還是很廣泛的,比如,在自定義view里或者解決滑動嵌套(其實google官方是不支持滑動嵌套的方式的,但是實際項目中還是有很多這種**的設(shè)計的)的時候。

理解事件分發(fā)的機(jī)制首先要理解三個方法:

  • boolean dispatchTouchEvent (MotionEvent ev)
dispatchTouchEvent.png

官方文檔上解釋很簡單就就一句話,分發(fā)事件到目標(biāo)視圖,返回結(jié)果是boolean類型的,表示是否消耗該事件,返回true表示事件會被處理,否則相反。其結(jié)果受當(dāng)前view的onTouchEvent和下級view的dispatchTouchEvent的影響。

  • boolean onInterceptTouchEvent (MotionEvent ev)
onInterceptTouchEvent.png

官網(wǎng)說的很清楚了,實現(xiàn)這個方法是為了攔截屏幕的觸摸事件,其實這個方法是在dispatchTouchEvent內(nèi)部調(diào)用的。當(dāng)需要在onTouchEvent里實現(xiàn)相對復(fù)雜的交互時可以使用這個方法。dispatchTouchEvent返回true的話,表示一整個事件系列都只能交給這個view來處理了,而且dispatchTouchEvent不會也沒有必要再調(diào)用了。一旦這個view開始處理事件了,那么它必須消耗掉down事件,也就是說onTouchEvent必須返回true,否則的話這一事件序列的其它剩余事件就不會接受到了,事件會重新交給父元素去處理。類似與如果上級交給你一件事,你沒有做好,那么同類的事上級短期內(nèi)是不會再交給你的。

  • boolean onTouchEvent (MotionEvent ev)
onTouchEvent.png

這個方法官網(wǎng)描述也比較簡單,主要是處理觸摸事件,分發(fā)onClickListener回調(diào)方法。需要注意的是,如果這個方法返回true表示這個事件被消耗掉了,否則這個事件不會再接受到同序列的其它事件,并且事件最終會回到上級去處理。另外,還需要注意的一點(diǎn)是在view中,onTouchListener的優(yōu)先級要比onTouchEvent要高,而OnClickListener的優(yōu)先級確實最低的,處于事件傳遞的末尾。如果view中設(shè)置了onTouchListener,事件的處理還得看onTouchListener的回調(diào)函數(shù)onTouch的返回值了,返回值是false的話onTouchEvent就被調(diào)用,否則不會調(diào)用。

至于這三者的關(guān)系其實網(wǎng)上的到處都有說,但是我覺得最簡潔明了的還是一段偽代碼:

public boolean dispatchTouchEvent(MotionEvent ev){
        boolean consume = false;
        if (onInterceptTouchEvent(ev)){
            consume = onTouchEvent(ev);
        }else {
            consume = child.dispatchTouchEvent(ev);
        }
        return consume;
            
    }

當(dāng)點(diǎn)擊事件產(chǎn)生后,首先會調(diào)用dispatchTouchEvent,如果onInterceptTouchEvent返回true表示他要攔截事件,接著onTouchEvent就會被調(diào)用。如果onInterceptTouchEvent返回false ,那么表示當(dāng)前view不會攔截事件,那么這個事件就會繼續(xù)傳遞到子view,于是,子view的dispatchTouchEvent方法調(diào)用,一直反復(fù)直到事件被處理。

接下來,看看源碼中的事件處理吧:
點(diǎn)擊事件發(fā)生時,首先傳遞到activity,然后acitivty在分發(fā)。

  /**
     * 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();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

activty把事件交給了Window來分發(fā),如果返回true則事件到此為止了,否則就是此事件子view都沒有處理,又交給activty的onTouchEvent來處理了。

我們再看Window的唯一的實現(xiàn)類PhoneWindow的事件分發(fā)方法。

    @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);
    }```
可以看到事件繼續(xù)交給了頂層View DecorView了,頂層布局一般都是ViewGroup,DecorView也不例外,其實它的實現(xiàn)類是繼承于FrameLayout的。我們按住shift鍵繼續(xù)往里點(diǎn)擊??梢钥吹絍iewGroup里的dispatchTouchEvent方法。
源碼太長了,這里只貼出一部分,在2206~2221行的這一段代碼里主要是判斷事件是否會被攔截。
        // 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;
        }
由上面可以看出只有在down事件和mFirstTouchTarget != null時才需要判斷,否則事件都是要攔截的。mFirstTouchTarget是"接受觸摸事件的View"所組成的單鏈表,一旦ViewGroup子元素成功處理事件時mFirstTouchTarget就會被賦值。也就是說,只要當(dāng)前ViewGroup不攔截事件那么 mFirstTouchTarget就不會為空。

當(dāng)Viewgroup不攔截事件時,事件將會交給它的子view來處理
                     // 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);

                        // If there is a view that has accessibility focus we want it
                        // to get the event first and if not handled we will perform a
                        // normal dispatch. We may do a double iteration but this is
                        // safer given the timeframe.
                        if (childWithAccessibilityFocus != null) {
                            if (childWithAccessibilityFocus != child) {
                                continue;
                            }
                            childWithAccessibilityFocus = null;
                            i = childrenCount - 1;
                        }

                        if (!canViewReceivePointerEvents(child)
                                || !isTransformedTouchPointInView(x, y, child, null)) {
                            ev.setTargetAccessibilityFocus(false);
                            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();
                            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;
                        }
遍歷子元素,如果事件的坐標(biāo)是在子元素的區(qū)域內(nèi)或者子元素在播放動畫,那么子元素就能夠接受收事件
跟進(jìn)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;
}

child不是null時,事件就交給子 view的dispatchTouchEvent來處理了?,F(xiàn)在我們來看看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;
        }
    }

    if (!result && mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
    }

    // Clean up after nested scrolls if this is the end of a gesture;
    // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
    // of the gesture.
    if (actionMasked == MotionEvent.ACTION_UP ||
            actionMasked == MotionEvent.ACTION_CANCEL ||
            (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
        stopNestedScroll();
    }

    return result;```

view 無需再向下傳遞事件了,所以只能自己處理了。源碼中,首先會判斷OnTouchListener是否為null。如果onTouch方法返回true,那么onTouchEvent方法便不會調(diào)用。因此可見OnTouchListener的優(yōu)先級還是高于onTouchEvent的。

看源碼很累啊。。。。。。

分析參考《Android開發(fā)藝術(shù)探索》

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容