Android源碼View事件分發(fā)和消費(fèi)詳解.md

我們都知道淫奔,用戶與app進(jìn)行交互都是通過activity來進(jìn)行的,而我們平時(shí)在activity中設(shè)置的view是怎么接收到用戶交互的事件呢怨绣,activity與view又有怎么樣的層級(jí)關(guān)系呢?我們來看一個(gè)很簡(jiǎn)單的頁(yè)面:

圖一

image

圖二

image.png

圖三

image.png

從三張圖我們可知,我們?cè)赼ctivity中通過setContentView設(shè)置的view就是圖一中的ContentViews部分钻注,它的根布局是FrameLayout,也是圖二中的紅色區(qū)域配猫。圖三中的紅色區(qū)域就是圖一中的TitleView幅恋。知道了activity與view的層級(jí)關(guān)系后,那么事件是怎么一步步傳到view中的呢泵肄?

首先來看Activity中的實(shí)現(xiàn):


<pre style="margin: 0.667rem 0px; color: rgb(0, 0, 0); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; font-family: Menlo; font-size: 9pt;">/**
 * 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);
}</pre>

大概意思就是捆交,如果Window的superDispatchTouchEvent返回true,表示Activity將該事件傳遞給Window來處理腐巢,如果返回false品追,則Activity自行處理該事件,Activity的onTouchEvent將會(huì)被調(diào)用冯丙,


<pre style="margin: 0.667rem 0px; color: rgb(0, 0, 0); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; font-family: Menlo; font-size: 9pt;">/**
 * Called when a touch screen event was not handled by any of the views * under it.  This is most useful to process touch events that happen * outside of your window bounds, where there is no view to receive it. * * @param event The touch screen event being processed.
 * * @return Return true if you have consumed the event, false if you haven't.
 * The default implementation always returns false. */ public boolean onTouchEvent(MotionEvent event) {
    if (mWindow.shouldCloseOnTouch(this, event)) {
        finish();
        return true;
    }

    return false;
}</pre>

下面再來看看Window的superDispatchTouchEvent返回true的情況肉瓦,由于Window的實(shí)現(xiàn)類為PhoneWindow,


<pre style="margin: 0.667rem 0px; color: rgb(0, 0, 0); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; font-family: Menlo; font-size: 9pt;">@Override public boolean superDispatchTouchEvent(MotionEvent event) {
    return mDecor.superDispatchTouchEvent(event);
}</pre>

有此可知調(diào)用了mDecor胃惜,mDecor就是DecorView泞莉,是根View,繼承至FrameLayout


<pre style="margin: 0.667rem 0px; color: rgb(0, 0, 0); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; font-family: Menlo; font-size: 9pt;">public boolean superDispatchTouchEvent(MotionEvent event) {
    return super.dispatchTouchEvent(event);
}</pre>

關(guān)于點(diǎn)擊事件如何在View中進(jìn)行分發(fā)船殉,點(diǎn)擊事件到達(dá)頂級(jí)view(一般是一個(gè)ViewGroup)鲫趁,會(huì)調(diào)用ViewGroup的dispatchTouchEvent方法,當(dāng)ACTION_DOWN事件發(fā)生后捺弦,如果ViewGroup選擇攔截該事件饮寞,那么接下來的ACTION_MOVE和ACTION_UP等這一事件序列的所有事件都不能被傳遞給ViewGroup的子View孝扛,都交給了ViewGroup進(jìn)行處理,所以說幽崩,ViewGroup不能攔截ACTION_DOWN事件苦始,否則子view將接收不到任何事件。ViewGroup不攔截ACTION_DOWN事件慌申,則交給子View進(jìn)行出來陌选,接著會(huì)調(diào)用子view的dispatchTouchEvent事件,如果子view的dispatchTouchEvent返回true表示消費(fèi)該事件蹄溉,否則表示不消費(fèi)該事件(會(huì)將該事件又返回給父ViewGroup進(jìn)行處理)咨油。

[圖片上傳失敗...(image-e9c0ad-1624893293481)]

如果事件交由ViewGroup進(jìn)行處理,執(zhí)行ViewGroup的超類View的dispatchTouchEvent方法柒爵,這時(shí)如果ViewGroup的mOnTouchListener被設(shè)置了役电,就會(huì)執(zhí)行OnTouchListener的onTouch方法,如果onTouch方法返回false棉胀,則接著會(huì)執(zhí)行onTouchEvent方法


<pre style="margin: 0.667rem 0px; color: rgb(0, 0, 0); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; font-family: Menlo; font-size: 9pt;">public boolean onTouchEvent(MotionEvent event) {
    final float x = event.getX();
    final float y = event.getY();
    final int viewFlags = mViewFlags;
    final int action = event.getAction();

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

                    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();
                            }
                            if (!post(mPerformClick)) {
                                performClick();
                            }
                        }
                    }

                    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);
                    checkForLongClick(0, x, y);
                }
                break;

            case MotionEvent.ACTION_CANCEL:
                if (clickable) {
                    setPressed(false);
                }
                removeTapCallback();
                removeLongPressCallback();
                mInContextButtonPress = false;
                mHasPerformedLongPress = false;
                mIgnoreNextUpEvent = false;
                mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                break;

            case MotionEvent.ACTION_MOVE:
                if (clickable) {
                    drawableHotspotChanged(x, y);
                }

                // Be lenient about moving outside of buttons
 if (!pointInView(x, y, mTouchSlop)) {
                    // Outside button
 // Remove any future long press/tap checks removeTapCallback();
                    removeLongPressCallback();
                    if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                        setPressed(false);
                    }
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                }
                break;
        }

        return true;
    }

    return false;
}</pre>

onTouchEvent會(huì)判斷該ViewGroup是否是可點(diǎn)擊的法瑟,也就是是否設(shè)置了mOnClickListener,如果設(shè)置了表示消費(fèi)該事件唁奢,onClick將會(huì)被調(diào)用霎挟。否則也就表示不消費(fèi)該事件,該事件還是會(huì)被拋給當(dāng)前的父View進(jìn)行處理麻掸。當(dāng)ViewGroup不攔截此事件酥夭,會(huì)交給子View進(jìn)行處理,然后再一次執(zhí)行dispatchTouchEvent方法脊奋。到此為止熬北,事件已經(jīng)從頂級(jí)View傳遞給了下一層的View,接下來的傳遞過程和頂級(jí)View是一致的诚隙,如此循環(huán)蒜埋,完成整個(gè)事件的分發(fā)。

所以我們接著看ViewGroup的dispatchTouchEvent最楷,

[圖片上傳失敗...(image-72149b-1624893293479)]

當(dāng)發(fā)生ACTION_DOWN事件時(shí),cancelAndClearTouchTargets會(huì)將mFirstTouchTarget重置為null待错,resetTouchState會(huì)將mGroupFlags置為0籽孙。

從上面代碼我們可以看出,ViewGroup在如下兩種情況下會(huì)判斷是否要攔截當(dāng)前事件:事件類型為ACTION_DOWN或者mFirstTouchTarget != null火俄,ACTION_DOWM 好理解犯建,那么mFirstTouchTarget是什么呢,由后面的代碼可知瓜客,mFirstTouchTarget在ViewGroup將事件傳遞給子view時(shí)适瓦,mFirstTouchTarget會(huì)被賦值并被指向子元素竿开。


<pre style="margin: 0.667rem 0px; color: rgb(0, 0, 0); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; font-family: Menlo; font-size: 9pt;">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;
}</pre>


<pre style="margin: 0.667rem 0px; color: rgb(0, 0, 0); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; font-family: Menlo; font-size: 9pt;">/**
 * Adds a touch target for specified child to the beginning of the list. * Assumes the target child is not already present. */ private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
    final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
    target.next = mFirstTouchTarget;
    mFirstTouchTarget = target;
    return target;
}</pre>

也就是當(dāng)ViewGroup不攔截事件并將事件交由子元素處理時(shí),mFirstTouchTarget != null玻熙。反過來否彩,一旦ViewGroup需要攔截此事件,mFirstTouchTarget != null就不成立了嗦随。那么當(dāng)ACTION_UP和ACTION_MOVE事件到來時(shí)列荔,actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null就不成立了,將導(dǎo)致ViewGroup的onInterceptTouchEvent不會(huì)被調(diào)用枚尼,intercepted為true贴浙,并且同一事件序列的其他事件也默認(rèn)交給ViewGroup處理。

當(dāng)然署恍,這里有一種特殊情況崎溃,那就是FLAG_DISALLOW_INTERCEPT標(biāo)記位,這個(gè)標(biāo)記位是通過requestDisallowInterceptTouchEvent方法設(shè)置的盯质,


<pre style="margin: 0.667rem 0px; color: rgb(0, 0, 0); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; font-family: Menlo; font-size: 9pt;">/**
 * Called when a child does not want this parent and its ancestors to * intercept touch events with * {@link ViewGroup#onInterceptTouchEvent(MotionEvent)}.
 * * <p>This parent should pass this call onto its parents. This parent must obey
 * this request for the duration of the touch (that is, only clear the flag * after this parent has received an up or a cancel.</p>  ** @param disallowIntercept True if the child does not want the parent to
 *            intercept touch events. */ public void requestDisallowInterceptTouchEvent(boolean disallowIntercept);</pre>

一般用于子View中袁串。FLAG_DISALLOW_INTERCEPT一旦設(shè)置后,ViewGroup將無(wú)法攔截除了ACTION_DOWN以外的點(diǎn)擊事件唤殴。為什么說出了ACTION_DOWN以外其他點(diǎn)擊事件般婆,是因?yàn)榘l(fā)生ACTION_DOWN事件時(shí),會(huì)重置mGroupFlags標(biāo)記位朵逝,還會(huì)置mFirstTouchTarget為null蔚袍,將導(dǎo)致子View設(shè)置的標(biāo)記位失效。因此當(dāng)發(fā)生ACTION_DOWN事件時(shí)配名,ViewGroup總是詢問自己是否要攔截事件啤咽,從上面代碼就可以看出。當(dāng)ViewGroup決定攔截事件時(shí)渠脉,后續(xù)這一事件序列里的所有事件都默認(rèn)交給ViewGroup自己處理并且不再調(diào)用onInterceptTouchEvent方法宇整。設(shè)置mGroupFlags為FLAG_DISALLOW_INTERCEPT的作用就是讓ViewGroup不再攔截事件,前提時(shí)ACTION_DOWN事件沒有被ViewGroup攔截芋膘。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末鳞青,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子为朋,更是在濱河造成了極大的恐慌臂拓,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,406評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件习寸,死亡現(xiàn)場(chǎng)離奇詭異胶惰,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)霞溪,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門孵滞,熙熙樓的掌柜王于貴愁眉苦臉地迎上來中捆,“玉大人,你說我怎么就攤上這事坊饶⌒刮保” “怎么了?”我有些...
    開封第一講書人閱讀 163,711評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵幼东,是天一觀的道長(zhǎng)臂容。 經(jīng)常有香客問我,道長(zhǎng)根蟹,這世上最難降的妖魔是什么脓杉? 我笑而不...
    開封第一講書人閱讀 58,380評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮简逮,結(jié)果婚禮上球散,老公的妹妹穿的比我還像新娘。我一直安慰自己散庶,他們只是感情好蕉堰,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著悲龟,像睡著了一般屋讶。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上须教,一...
    開封第一講書人閱讀 51,301評(píng)論 1 301
  • 那天皿渗,我揣著相機(jī)與錄音,去河邊找鬼轻腺。 笑死乐疆,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的贬养。 我是一名探鬼主播挤土,決...
    沈念sama閱讀 40,145評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼误算!你這毒婦竟也來了仰美?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,008評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤儿礼,失蹤者是張志新(化名)和其女友劉穎筒占,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蜘犁,經(jīng)...
    沈念sama閱讀 45,443評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評(píng)論 3 334
  • 正文 我和宋清朗相戀三年止邮,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了这橙。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片奏窑。...
    茶點(diǎn)故事閱讀 39,795評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖屈扎,靈堂內(nèi)的尸體忽然破棺而出埃唯,到底是詐尸還是另有隱情,我是刑警寧澤鹰晨,帶...
    沈念sama閱讀 35,501評(píng)論 5 345
  • 正文 年R本政府宣布墨叛,位于F島的核電站,受9級(jí)特大地震影響模蜡,放射性物質(zhì)發(fā)生泄漏漠趁。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評(píng)論 3 328
  • 文/蒙蒙 一忍疾、第九天 我趴在偏房一處隱蔽的房頂上張望闯传。 院中可真熱鬧,春花似錦卤妒、人聲如沸甥绿。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)共缕。三九已至,卻和暖如春士复,著一層夾襖步出監(jiān)牢的瞬間图谷,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工判没, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留蜓萄,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,899評(píng)論 2 370
  • 正文 我出身青樓澄峰,卻偏偏與公主長(zhǎng)得像嫉沽,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子俏竞,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評(píng)論 2 354

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