從源碼解析android事件分發(fā)之

首先惧互,我們分析不做任何處理事件是如何分發(fā)的

android 事件分發(fā)是我們開發(fā)安卓必須知道的知識點(diǎn)鸦概,無論是開發(fā)中還是面試梨撞,都經(jīng)常遇到事件分發(fā)類的問題何鸡,今天我們就從源碼層進(jìn)行深度剖析。

首先我們給定一個布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

</RelativeLayout>

這個布局我們不做任何處理筛璧,那么當(dāng)我點(diǎn)擊 Hello World 這個文本控件后逸绎,會有一個點(diǎn)擊事件,下面就讓我們來追蹤這個點(diǎn)擊事件
首先我們需要知道誰最先接收到這個點(diǎn)擊事件夭谤,我來告訴你棺牧,就是在源碼 Activity 中的dispatchTouchEvent方法,為什么是這個方法呢朗儒,就是這么設(shè)計的颊乘,手點(diǎn)擊屏幕,觸發(fā)屏幕傳感器醉锄,再通過底層硬件代碼調(diào)用乏悄,然后就到這個方法里了。

/**
     * 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.
      (調(diào)用以處理觸摸屏事件恳不。您可以覆蓋此選項(xiàng)檩小,以便在將所有觸摸屏事件發(fā)送到窗口之前截獲它們。對于應(yīng)該正常處理的觸摸屏事件烟勋,一定要調(diào)用此實(shí)現(xiàn)规求。)
     *
     * @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);
    }

記住標(biāo)題,我們假設(shè)的是不做任何處理卵惦,然后看事件的分發(fā)

我們在方法中可以看到

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

因?yàn)椴蛔鋈魏翁幚碜柚祝赃@個地方不能return ture,
也就是說getWindow().superDispatchTouchEvent(ev)要為false,
我們進(jìn)入getWindow().superDispatchTouchEvent(ev)
然后在Window文件中發(fā)現(xiàn)了抽象方法

public abstract boolean superDispatchTouchEvent(MotionEvent event);

然后我們進(jìn)入Window抽象類的實(shí)現(xiàn)類PhoneWindow,找到方法

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

進(jìn)入mDecor.superDispatchTouchEvent(event)
然后來到 DecorView

public boolean superDispatchTouchEvent(MotionEvent event) {
    return super.dispatchTouchEvent(event);
}

這個時候來到了ViewGroup文件的dispatchTouchEvent方法

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }

        // If the event targets the accessibility focused view and this is it, start
        // normal event dispatch. Maybe a descendant is what will handle the click.
        if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
            ev.setTargetAccessibilityFocus(false);
        }

        boolean handled = false;
        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.
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }

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

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

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

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

                    if (newTouchTarget == null && mFirstTouchTarget != null) {
                        // Did not find a child to receive the event.
                        // Assign the pointer to the least recently added target.
                        newTouchTarget = mFirstTouchTarget;
                        while (newTouchTarget.next != null) {
                            newTouchTarget = newTouchTarget.next;
                        }
                        newTouchTarget.pointerIdBits |= idBitsToAssign;
                    }
                }
            }

            // Dispatch to touch targets.
            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;
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            handled = true;
                        }
                        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);
        }
        return handled;
    }

以上是dispatchTouchEvent方法的全部內(nèi)容,下面我拆分講解
首先我們假設(shè)文章開頭給的布局里面沮尿,RelativeLayout 外面沒有別的布局了冕茅,因?yàn)镽elativeLayout 里面還有一個TextView,所以這個點(diǎn)擊事件必然還要向下傳遞,所以我們直接來到遍歷子View的地方

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

在這里我們找到了for循環(huán)蛹找,在循環(huán)里,我們需要注意child 的處理
在下面我們發(fā)現(xiàn)代碼

if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign))

很顯然哨坪,這里dispatchTransformedTouchEvent也需要返回false,我們進(jìn)入該方法,找到代碼塊

      if (newPointerIdBits == oldPointerIdBits) {
            if (child == null || child.hasIdentityMatrix()) {
                if (child == null) {
                    handled = super.dispatchTouchEvent(event);
                } else {
                    final float offsetX = mScrollX - child.mLeft;
                    final float offsetY = mScrollY - child.mTop;
                    event.offsetLocation(offsetX, offsetY);

                    handled = child.dispatchTouchEvent(event);

                    event.offsetLocation(-offsetX, -offsetY);
                }
                return handled;
            }
            transformedEvent = MotionEvent.obtain(event);
        } else {
            transformedEvent = event.split(newPointerIdBits);
        }

很顯然庸疾,我們這里還有TextView,所以這個View為TextView,不為空当编,點(diǎn)擊事件又給了子View的dispatchTouchEvent届慈,就是調(diào)用了

handled = child.dispatchTouchEvent(event);

由于我們未做任何處理,所以 child.dispatchTouchEvent(event) 也要返回false,我們進(jìn)入該方法,發(fā)現(xiàn)代碼塊

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;
}
這里正好可以補(bǔ)充一個知識點(diǎn)金顿,我們發(fā)現(xiàn)如果 li.mOnTouchListener != null臊泌,那么就會調(diào)用 && li.mOnTouchListener.onTouch(this, event),然后返回了true,默認(rèn)消費(fèi)了這次的事件揍拆,這就是為什么如果我們設(shè)置了OnTouchListener后就不會再調(diào)用onTouch方法

當(dāng)然了渠概,這個地方li.mOnTouchListener肯定為空,所以事件又給了onTouchEvent方法嫂拴,當(dāng)然播揪,這個地方也還是返回false,然后我再重新回到View的dispatchTouchEvent,還是返回false,再繼續(xù)返回至ViewGroup的dispatchTouchEvent方法里筒狠,就是循環(huán)遍歷子View的地方猪狈,進(jìn)過這一輪遍歷,沒有一個子View消費(fèi)點(diǎn)擊事件的辩恼,那么代碼繼續(xù)往下走雇庙,發(fā)現(xiàn)了代碼塊

if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            }

以為沒有子View消費(fèi),所以mFirstTouchTarget 為空灶伊,因?yàn)閂iewGroup也沒有消費(fèi)點(diǎn)擊事件疆前,所以dispatchTransformedTouchEvent還是返回false,我們注意入?yún)ⅲl(fā)現(xiàn)傳View的地方傳了一個null,我們進(jìn)入該方法谁帕,還是同樣的代碼

      if (newPointerIdBits == oldPointerIdBits) {
            if (child == null || child.hasIdentityMatrix()) {
                if (child == null) {
                    handled = super.dispatchTouchEvent(event);
                } else {
                    final float offsetX = mScrollX - child.mLeft;
                    final float offsetY = mScrollY - child.mTop;
                    event.offsetLocation(offsetX, offsetY);

                    handled = child.dispatchTouchEvent(event);

                    event.offsetLocation(-offsetX, -offsetY);
                }
                return handled;
            }
            transformedEvent = MotionEvent.obtain(event);
        } else {
            transformedEvent = event.split(newPointerIdBits);
        }

只不過這次不在是child.dispatchTouchEvent(event);峡继,而是super.dispatchTouchEvent(event);
同理進(jìn)去我們發(fā)現(xiàn)它把事件又給了自己的onTouchEvent,然后繼續(xù)返回false
此時代碼再繼續(xù)往下走匈挖,方法結(jié)束碾牌,返回false,這個時候又進(jìn)入了Activity的dispatchTouchEvent方法,就是一開始寫的這個方法

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

然后getWindow().superDispatchTouchEvent(ev)為false,直接返回了自己的onTouchEvent儡循,自此一個點(diǎn)擊事件的旅程結(jié)束


圖片.png

這個ViewGroup是一個遞歸調(diào)用舶吗,其實(shí)這個地方有好多個ViewGroup

網(wǎng)上也有很多博客是這么說的

圖片.png

注意,這個是不嚴(yán)謹(jǐn)?shù)脑裣ィ蛘哒f是錯誤的

好誓琼,以上是不做處理,那么下面我寫幾種情況

1肴捉、ViewGroup 的 onTouchEvent進(jìn)行自定義處理腹侣,返回true

圖片.png

2、ViewGroup 的 onInterceptTouchEvent進(jìn)行自定義處理齿穗,返回true

圖片.png

3傲隶、View 的 onTouchEvent進(jìn)行自定義處理,返回true

圖片.png
版權(quán)聲明:個人原創(chuàng)窃页,若轉(zhuǎn)載跺株,請注明出處
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末复濒,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子乒省,更是在濱河造成了極大的恐慌巧颈,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,311評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件袖扛,死亡現(xiàn)場離奇詭異砸泛,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)攻锰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,339評論 2 382
  • 文/潘曉璐 我一進(jìn)店門晾嘶,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人娶吞,你說我怎么就攤上這事垒迂。” “怎么了妒蛇?”我有些...
    開封第一講書人閱讀 152,671評論 0 342
  • 文/不壞的土叔 我叫張陵机断,是天一觀的道長。 經(jīng)常有香客問我绣夺,道長吏奸,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,252評論 1 279
  • 正文 為了忘掉前任陶耍,我火速辦了婚禮奋蔚,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘烈钞。我一直安慰自己泊碑,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,253評論 5 371
  • 文/花漫 我一把揭開白布毯欣。 她就那樣靜靜地躺著馒过,像睡著了一般。 火紅的嫁衣襯著肌膚如雪酗钞。 梳的紋絲不亂的頭發(fā)上腹忽,一...
    開封第一講書人閱讀 49,031評論 1 285
  • 那天,我揣著相機(jī)與錄音砚作,去河邊找鬼窘奏。 笑死,一個胖子當(dāng)著我的面吹牛葫录,可吹牛的內(nèi)容都是我干的蔼夜。 我是一名探鬼主播,決...
    沈念sama閱讀 38,340評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼压昼,長吁一口氣:“原來是場噩夢啊……” “哼求冷!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起窍霞,我...
    開封第一講書人閱讀 36,973評論 0 259
  • 序言:老撾萬榮一對情侶失蹤匠题,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后但金,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體韭山,經(jīng)...
    沈念sama閱讀 43,466評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,937評論 2 323
  • 正文 我和宋清朗相戀三年冷溃,在試婚紗的時候發(fā)現(xiàn)自己被綠了钱磅。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,039評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡似枕,死狀恐怖盖淡,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情凿歼,我是刑警寧澤褪迟,帶...
    沈念sama閱讀 33,701評論 4 323
  • 正文 年R本政府宣布,位于F島的核電站答憔,受9級特大地震影響味赃,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜虐拓,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,254評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望蓉驹。 院中可真熱鬧,春花似錦戒幔、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,259評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽敢订。三九已至王污,卻和暖如春楚午,著一層夾襖步出監(jiān)牢的瞬間昭齐,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工阱驾, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留就谜,地道東北人里覆。 一個月前我還...
    沈念sama閱讀 45,497評論 2 354
  • 正文 我出身青樓丧荐,卻偏偏與公主長得像,于是被迫代替她去往敵國和親喧枷。 傳聞我的和親對象是個殘疾皇子虹统,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,786評論 2 345

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