Android事件機制源碼理解

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

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

  • boolean dispatchTouchEvent (MotionEvent ev)
dispatchTouchEvent.png

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

  • boolean onInterceptTouchEvent (MotionEvent ev)
onInterceptTouchEvent.png

官網(wǎng)說的很清楚了啥繁,實現(xiàn)這個方法是為了攔截屏幕的觸摸事件荒叶,其實這個方法是在dispatchTouchEvent內(nèi)部調(diào)用的。當需要在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表示這個事件被消耗掉了,否則這個事件不會再接受到同序列的其它事件芋忿,并且事件最終會回到上級去處理炸客。另外,還需要注意的一點是在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;
            
    }

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

接下來稽莉,看看源碼中的事件處理吧:
點擊事件發(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ù)往里點擊聋亡。可以看到ViewGroup里的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就會被賦值垢袱。也就是說,只要當前ViewGroup不攔截事件那么 mFirstTouchTarget就不會為空港柜。

當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;
                        }
遍歷子元素,如果事件的坐標是在子元素的區(qū)域內(nèi)或者子元素在播放動畫夏醉,那么子元素就能夠接受收事件
跟進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來處理了。現(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)系作者
  • 序言:七十年代末福也,一起剝皮案震驚了整個濱河市孝冒,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌拟杉,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,454評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件量承,死亡現(xiàn)場離奇詭異搬设,居然都是意外死亡,警方通過查閱死者的電腦和手機撕捍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,553評論 3 385
  • 文/潘曉璐 我一進店門拿穴,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人忧风,你說我怎么就攤上這事默色。” “怎么了狮腿?”我有些...
    開封第一講書人閱讀 157,921評論 0 348
  • 文/不壞的土叔 我叫張陵腿宰,是天一觀的道長。 經(jīng)常有香客問我缘厢,道長吃度,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,648評論 1 284
  • 正文 為了忘掉前任贴硫,我火速辦了婚禮椿每,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘英遭。我一直安慰自己间护,他們只是感情好,可當我...
    茶點故事閱讀 65,770評論 6 386
  • 文/花漫 我一把揭開白布挖诸。 她就那樣靜靜地躺著汁尺,像睡著了一般。 火紅的嫁衣襯著肌膚如雪税灌。 梳的紋絲不亂的頭發(fā)上均函,一...
    開封第一講書人閱讀 49,950評論 1 291
  • 那天亿虽,我揣著相機與錄音,去河邊找鬼苞也。 笑死洛勉,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的如迟。 我是一名探鬼主播收毫,決...
    沈念sama閱讀 39,090評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼殷勘!你這毒婦竟也來了此再?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,817評論 0 268
  • 序言:老撾萬榮一對情侶失蹤玲销,失蹤者是張志新(化名)和其女友劉穎输拇,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體贤斜,經(jīng)...
    沈念sama閱讀 44,275評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡策吠,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,592評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了瘩绒。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片猴抹。...
    茶點故事閱讀 38,724評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖锁荔,靈堂內(nèi)的尸體忽然破棺而出蟀给,到底是詐尸還是另有隱情,我是刑警寧澤阳堕,帶...
    沈念sama閱讀 34,409評論 4 333
  • 正文 年R本政府宣布跋理,位于F島的核電站,受9級特大地震影響恬总,放射性物質(zhì)發(fā)生泄漏薪介。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 40,052評論 3 316
  • 文/蒙蒙 一越驻、第九天 我趴在偏房一處隱蔽的房頂上張望汁政。 院中可真熱鬧,春花似錦缀旁、人聲如沸记劈。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,815評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽目木。三九已至,卻和暖如春懊渡,著一層夾襖步出監(jiān)牢的瞬間刽射,已是汗流浹背军拟。 一陣腳步聲響...
    開封第一講書人閱讀 32,043評論 1 266
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留誓禁,地道東北人懈息。 一個月前我還...
    沈念sama閱讀 46,503評論 2 361
  • 正文 我出身青樓,卻偏偏與公主長得像摹恰,于是被迫代替她去往敵國和親辫继。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 43,627評論 2 350

推薦閱讀更多精彩內(nèi)容