Android6.0 ViewGroup/View 事件分發(fā)機制詳解

之前自認為對于Android的事件分發(fā)機制還算比較了解,直到前一陣偶然跟人探討該問題豫领,才發(fā)現(xiàn)自己以前的理解有誤抡柿,慚愧之余遂決定研習源碼,徹底弄明白Android的事件分發(fā)機制等恐,好了廢話少說洲劣,直接開干。

首先鼠锈,我們對Android中的touch事件做一下總結闪檬,主要分為以下幾類:

1、Action_Down 用戶手指觸碰到屏幕的那一刻购笆,會觸發(fā)該事件粗悯;
2、Action_Move 在觸碰到屏幕之后同欠,手指開始在屏幕上滑動样傍,會觸發(fā)Action_Move事件横缔;
3、Action_Up 在用戶手指從屏幕上離開那一刻開始衫哥,會觸發(fā)Action_Up事件茎刚;
4、Action_Cancel Cancel事件一般跟Up事件的處理是一樣的撤逢,是由系統(tǒng)代碼自己去觸發(fā)膛锭,比如子view的事件被父view給攔截了,之前被分發(fā)的子view就會被發(fā)送cancel事件蚊荣,或者用戶手指在滑動過程中移出了邊界初狰。另外,在有多點觸控事件時互例,還會陸續(xù)觸發(fā)ACTION_POINTER_DOWN奢入、ACTION_POINTER_UP等事件。

其次媳叨,我們知道Android中負責事件分發(fā)機制的方法主要有以下三個:

1腥光、dispatchTouchEvent(MotionEvent event) --- 分發(fā)事件
我們知道當用戶觸摸到手機屏幕時,最先接收到事件并進行相應處理的應該是最外層的Activity糊秆,所以我們來看看Activity中是如何對事件進行分發(fā)的武福。

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

從以上代碼中我們可以看到調用getWindow().superDispatchTouchEvent(),而這里的getWindow()返回的是Window抽象類痘番,其實就是PhoneWindow類艘儒,繼承于Window抽象類,然后調用PhoneWindow的superDispatchTouchEvent()夫偶,

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

從superDispatchTouchEvent()方法中可以看到,它又調用了mDecor的superDispatchTouchEvent()方法觉增,再看mDecor的superDispatchTouchEvent()方法兵拢,

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

而mDecor是何許人也,其實就是PhoneWindow中的一個內(nèi)部類DecorView的實例對象逾礁,是Activity的Window窗口中最根部的父容器说铃,我們平時在Activity的onCreate()方法中,通過setContentView()給設置的布局容器嘹履,都屬于mDecor的子View mContentView對象的子view腻扇,而DecorView又繼承于FrameLayout,F(xiàn)rameLayout又繼承于ViewGroup砾嫉,由此可知幼苛,Activity是如何將事件分發(fā)到相應的View當中去的:

Activity.dispatchTouchEvent(MotionEvent event) -> PhoneWindow.superDispatchTouchEvent(MotionEvent event) -> DecorView.superDispatchTouchEvent(MotionEvent event) -> FrameLayout.dispatchTouchEvent(MotionEvent event) -> ViewGroup.dispatchTouchEvent(MotionEvent event) -> 再逐級分發(fā)到各個ViewGroup/View當中去

另外從以上分析過程可以看出,有一點需注意焕刮,就是我們在繼承ViewGroup或其子類復寫dispatchTouchEvent時舶沿,在方法最后的返回值處墙杯,最好別直接寫成return true或者return false,而應寫成super.dispatchTouchEvent括荡,否則無法對事件繼續(xù)進行逐級分發(fā)高镐,因為在ViewGroup類的dispatchTouchEvent(MotionEvent event)方法中,會對該布局容器內(nèi)的所有子View進行遍歷畸冲,然后再進行事件分發(fā)嫉髓,詳細分發(fā)過程稍后會給出。
2邑闲、onInterceptTouchEvent(MotionEvent event) --- 攔截事件
onInterceptTouchEvent(MotionEvent event) 方法只存在于ViewGroup當中算行,是用來對布局容器內(nèi)子View的事件進行攔截的,如果父容器View對事件進行了攔截监憎,即return true纱意,則子View不會收到任何事件分發(fā)。
3鲸阔、onTouchEvent(MotionEvent event) --- 處理消費事件
onTouchEvent(MotionEvent event)方法如果返回true偷霉,則表示該事件被當前View給消費掉了,它的父View的onTouchEvent()后續(xù)都不會得到調用褐筛,而是通過dispatchTouchEvent()逐級向上返回true到Activity类少;如果沒人消費該事件,都返回false渔扎,則最終會交給Activity去進行處理硫狞。
在大致了解了dispatchTouchEvent、onInterceptTouchEvent晃痴、onTouchEvent的作用之后残吩,現(xiàn)在我們最需要理清的就是這三者之間的調用關系如何,為此我自己寫了一個測試Demo倘核,界面如下:


屏幕中有ViewGroupA泣侮、ViewGroupB、ViewC紧唱,依次進行嵌套
測試代碼如下:

<com.android.hanyee.widgets.ViewGroupA xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/viewGroupA"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@android:color/white">
android:id="@+id/viewGroupB"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="60dp"
android:orientation="vertical"
android:background="@android:color/holo_blue_dark">
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="60dp"
android:background="@android:color/holo_green_dark" />
public class ViewGroupA extends LinearLayout {
    public ViewGroupA(Context context) {
        super(context);
    }
    public ViewGroupA(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public ViewGroupA(Context context, AttributeSet attrs, int  defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        Log.d("hanyee", this.getClass().getSimpleName() + " onInterceptTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
        boolean result = super.onInterceptTouchEvent(ev);
        Log.d("hanyee", this.getClass().getSimpleName() + " onInterceptTouchEvent return super.onInterceptTouchEvent(ev)=" + result);
        return result;
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
        boolean result = super.dispatchTouchEvent(ev);
        Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent return super.dispatchTouchEvent(ev)= " + result);
        return result;
    }
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
        boolean result = super.onTouchEvent(ev);
        Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent         return super.onTouchEvent(ev)=" + result);
        return result;
    }
}

public class ViewGroupB extends LinearLayout {
    public ViewGroupB(Context context) {
        super(context);
    }
    public ViewGroupB(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public ViewGroupB(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        Log.d("hanyee", this.getClass().getSimpleName() + " onInterceptTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
        boolean result = super.onInterceptTouchEvent(ev);
        Log.d("hanyee", this.getClass().getSimpleName() + " onInterceptTouchEvent return super.onInterceptTouchEvent(ev)=" + result);
        return result;
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
        boolean result = super.dispatchTouchEvent(ev);
        Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent return super.dispatchTouchEvent(ev)= " + result);
        return result;
    }
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
        boolean result = super.onTouchEvent(ev);
        Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent return super.onTouchEvent(ev)=" + result);
        return result;
    }
}

public class ViewC extends View {
    public ViewC(Context context) {
        super(context);
    }
    public ViewC(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public ViewC(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
        boolean result = super.dispatchTouchEvent(ev);
        Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent return super.dispatchTouchEvent(ev)= " + result);
        return result;
    }
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
        boolean result = super.onTouchEvent(ev);
        Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent     return super.onTouchEvent(ev)=" + result);
        return result;
    }
}

測試情景1:ViewGroupA活尊、ViewGroupB、ViewC都沒有消費事件
測試結果如下圖:


由圖中l(wèi)og可以看出漏益,如果沒有任何view消費事件的話蛹锰,事件的傳遞順序如下:

ViewGroupA.dispatchTouchEvent -> ViewGroupA.onInterceptTouchEvent(return false, 沒有進行攔截) -> ViewGroupB.dispatchTouchEvent -> ViewGroupB.onInterceptTouchEvent(return false, 沒有進行攔截) -> ViewC.dispatchTouchEvent -> ViewC.onTouchEvent(return false, 沒有消費) -> ViewC.dispatchTouchEvent(return false, 將onTouchEvent的處理結果回傳給ViewGroupB) -> ViewGroupB.onTouchEvent(return false, 也沒有消費) -> ViewB.dispatchTouchEvent(return false, 將onTouchEvent的處理結果回傳給ViewGroupA) -> ViewGroupA.onTouchEvent(return false, 也沒有消費) -> ViewA.dispatchTouchEvent(return false, 最終將onTouchEvent的處理結果回傳給Activity) -> Activity對事件進行最終處理

看到這里大伙可能會有些疑問,怎么就只有Down事件绰疤,而沒有后續(xù)的Move铜犬、Up等事件,這是因為沒有任何子View消費Down事件,Down事件最終被最外層的Activity給處理掉了翎苫,所以后續(xù)的所有Move权埠、Up等事件都不會再分發(fā)給子View了,這里在后面的源碼分析時會提到煎谍。
測試情景2:ViewC消費了事件
測試結果如下圖:


由圖中的log可以看出攘蔽,一旦ViewC消費了Down事件,它的父容器ViewGroupB呐粘,祖父容器ViewGroupA的onTouchEvent都不會被調用了满俗,而是直接通過dispatchTouchEvent將Down以及后續(xù)的Move、Up事件的處理結果返回至Activity作岖。
測試情景3:僅點擊ViewGroupB唆垃,讓ViewGroupB消費事件
測試結果如下圖:


從圖中l(wèi)og可以看出,如果點擊ViewGroupB痘儡,事件根本就不會傳遞到ViewC辕万,ViewGroupB在消費了Down事件之后,再直接由父容器ViewGroupA的dispatchTouchEvent將ViewGroupB的onTouchEvent處理結果true回傳給Activity沉删,接下來后續(xù)的Move渐尿、Up事件都只會傳遞至ViewGroupB,而不會分發(fā)給ViewC矾瑰。
測試情景4:讓ViewGroupB對事件進行攔截
測試結果如圖:


從圖中l(wèi)og可以看出砖茸,如果ViewGroupB的onInterceptTouchEvent 返回true,對子view的事件進行攔截殴穴,則ViewC不會收到任何的點擊事件凉夯,事件流變成了ViewGroupA -->ViewGroupB --> ViewGroupA,而沒有經(jīng)過ViewC
通過上述幾種情景采幌,我們可以大致了解劲够,ViewGroupA的dispatchTouchEvent最先被調用,主要負責事件分發(fā)休傍,然后會調用其onInterceptTouchEvent再沧,如果返回true,則后續(xù)的ViewGroupB尊残、ViewC都不會收到任何的點擊事件,相反如果返回false淤堵,就放棄攔截事件寝衫,接著會遍歷調用子View的dispatchTouchEvent方法將事件分發(fā)給ViewGroupB,如果ViewGroupB也沒有攔截事件拐邪,則又會遍歷調用子View的dispatchTouchEvent方法將事件分發(fā)給ViewC慰毅,如果ViewC在onTouchEvent中消費了事件返回true,則會將true通過dispatchTouchEvent方法逐級返回給其父容器直至Activity中扎阶,而且不會調用各個父容器對應的onTouchEvent方法汹胃,如果子View在onTouchEvent中沒消費事件返回false婶芭,則通過dispatchTouchEvent方法將false返回給ViewGroupB,ViewGroupB就知道子View沒有消費事件着饥,就會調用自己的onTouchEvent來處理該事件犀农,然后同理遞歸著ViewC在onTouchEvent中對于事件的處理邏輯,直到ViewGroupA將事件處理完反饋給Activity宰掉。
前面列了這么多現(xiàn)象呵哨,并歸納總結出以上dispatchTouchEvent、onInterceptTouchEvent轨奄、onTouchEvent之間的調用關系孟害,相信大家對于Android事件的分發(fā)機制已經(jīng)有了較為清晰的認識,但作為一名程序員挪拟,知其然挨务,還得知其所以然,下面就帶領大家一起研讀下源碼玉组,看看到底為啥是這樣的調用關系谎柄。從上面的情景l(fā)og中大家應該可以看出,事件分發(fā)機制的最初始的入口就是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 accessiiblity 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 = buildOrderedChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = customOrder
                                    ? getChildDrawingOrder(childrenCount, i) : i;
                            final View child = (preorderedList == null)
                                    ? children[childIndex] : preorderedList.get(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;
    }

這方法看似比較長谷誓,但我們只挑比較重要的點來看,在第32行會根據(jù)disallowIntercept來判斷是否對子view來進行事件攔截吨凑,子view可以通過調用requestDisallowInterceptTouchEvent()方法來改變其值捍歪,如果可以進行攔截,則會調用onInterceptTouchEvent()方法鸵钝,根據(jù)其返回值來判斷需不需要對子View進行攔截糙臼,默認情況下onInterceptTouchEvent()方法返回的是false,所以如果我們在自定義View時如果想攔截的話恩商,可以重寫這個方法返回true就行了嗤瞎。
然后在第58行的if條件中,會根據(jù)是否取消canceled以及之前的是否攔截的標志intercepted來判斷是否走進下面的邏輯代碼塊幅垮,這里我們只看intercepted雷逆,如果沒有攔截,則會進入if后面的邏輯代碼塊粟矿,直到第89行的for循環(huán)凰棉,我們會看到ViewGroup在對所有子View進行遍歷,以方便接下來的事件分發(fā)陌粹,再看到107撒犀、108行的判斷,canViewReceivePointerEvents()用來判斷是否該View能夠接受處理事件,

    private static boolean canViewReceivePointerEvents(View child) {
        return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE
                || child.getAnimation() != null;
    }

可以看到只有當view處于可見狀態(tài)且沒有做動畫時才能接收處理事件或舞,再看isTransformedTouchPointInView()是用來判斷當前事件是否觸發(fā)在該view的范圍之內(nèi)荆姆,這里我們可以回想前面的測試情景3,當我們點擊ViewGroupB時映凳,ViewC完全沒有收到任何事件胆筒,就是因為點擊事件不在ViewC的范圍之類,在isTransformedTouchPointInView()進行判斷時就給過濾掉了魏宽,所以ViewC不會收到任何分發(fā)的事件腐泻。再看看第122行,會調用dispatchTransformedTouchEvent()來將事件分發(fā)給對應的view進行處理队询,讓我們進入其方法體看看派桩,

    private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        final boolean handled;

        // Canceling motions is a special case.  We don't need to perform any transformations
        // or filtering.  The important part is the action, not the contents.
        final int oldAction = event.getAction();
        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;
        }

        // Calculate the number of pointers to deliver.
        final int oldPointerIdBits = event.getPointerIdBits();
        final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;

        // If for some reason we ended up in an inconsistent state where it looks like we
        // might produce a motion event with no pointers in it, then drop the event.
        if (newPointerIdBits == 0) {
            return false;
        }

        // If the number of pointers is the same and we don't need to perform any fancy
        // irreversible transformations, then we can reuse the motion event for this
        // dispatch as long as we are careful to revert any changes we make.
        // Otherwise we need to make a copy.
        final MotionEvent transformedEvent;
        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);
        }

        // Perform any necessary transformations and dispatch.
        if (child == null) {
            handled = super.dispatchTouchEvent(transformedEvent);
        } else {
            final float offsetX = mScrollX - child.mLeft;
            final float offsetY = mScrollY - child.mTop;
            transformedEvent.offsetLocation(offsetX, offsetY);
            if (! child.hasIdentityMatrix()) {
                transformedEvent.transform(child.getInverseMatrix());
            }

            handled = child.dispatchTouchEvent(transformedEvent);
        }

        // Done.
        transformedEvent.recycle();
        return handled;
    }

我們看到在方法的末尾第55行,如果child為Null蚌斩,則會調用ViewGroup的父類View的dispatchTouchEvent铆惑,否則就會調用child自身的dispatchTouchEvent方法進行事件分發(fā)處理。如果child是ViewGroup送膳,則會又遞歸調用ViewGroup的dispatchTouchEvent方法邏輯進行事件分發(fā)员魏,如果是View,則跟child為Null情況一樣叠聋,都是會調到View的dispatchTouchEvent方法撕阎,接下來我們看看View的dispatchTouchEvent方法,

    public boolean dispatchTouchEvent(MotionEvent event) {
        // If the event should be handled by accessibility focus first.
        if (event.isTargetAccessibilityFocus()) {
            // We don't have focus or no virtual descendant has it, do not handle the event.
            if (!isAccessibilityFocusedViewOrHost()) {
                return false;
            }
            // We have focus and got the event, then use normal event dispatch.
            event.setTargetAccessibilityFocus(false);
        }

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

同樣我們撿重點的看碌补,第23行用來做過濾虏束,看是否有窗口覆蓋在上面,第27~29行三個判斷條件說明了厦章,當View的touch事件監(jiān)聽器不為空镇匀,View是enable狀態(tài),且touch事件監(jiān)聽回調方法onTouch方法返回true三個條件同時滿足時袜啃,則會最終返回true汗侵,而且第33行的onTouchEvent方法都不會得到執(zhí)行,這說明View的OnTouchListener監(jiān)聽回調的優(yōu)先級要高于onTouchEvent群发,如果我們給View設置了OnTouchListener監(jiān)聽晰韵,并且在回調方法onTouch()中返回true,View的onTouchEvent就得不到執(zhí)行熟妓,其dispatchTouchEvent方法就會直接返回true給父容器雪猪,相反如果返回false,或者沒有設置OnTouchListener監(jiān)聽滑蚯,才會執(zhí)行onTouchEvent()方法對分發(fā)來的事件進行處理。接著再去看看onTouchEvent()中如何對事件進行處理的,

    public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                setPressed(false);
            }
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
            return (((viewFlags & CLICKABLE) == CLICKABLE
                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
        }

        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }

        if (((viewFlags & CLICKABLE) == CLICKABLE ||
                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
            switch (action) {
                case MotionEvent.ACTION_UP:
                    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:
                    mHasPerformedLongPress = false;

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

                case MotionEvent.ACTION_CANCEL:
                    setPressed(false);
                    removeTapCallback();
                    removeLongPressCallback();
                    mInContextButtonPress = false;
                    mHasPerformedLongPress = false;
                    mIgnoreNextUpEvent = false;
                    break;

                case MotionEvent.ACTION_MOVE:
                    drawableHotspotChanged(x, y);

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

                            setPressed(false);
                        }
                    }
                    break;
            }

            return true;
        }

        return false;
    }

從第716行可以看出告材,當View為disable狀態(tài)坤次,而又clickable時,是會消費掉事件的斥赋,只不過在界面上沒有任何的響應缰猴。第1822行,關于TouchDelegate疤剑,根據(jù)對官方文檔的理解就是說有兩個View, ViewB在ViewA中滑绒,ViewA比較大,如果我們想點擊ViewA的時候隘膘,讓ViewB去響應點擊事件疑故,這時候就需要使用到TouchDelegate, 簡單的理解就是如果該View有自己的事件委托處理人弯菊,就交給委托人處理纵势。從第24~26行可以看出,只有當View是可點擊狀態(tài)時管钳,才會進入對應各種事件的詳細處理邏輯钦铁,否則會直接返回false,表明該事件沒有被消費才漆。在第59行牛曹,可以看到在Action_Up事件被觸發(fā)時,會執(zhí)行performClick()醇滥,也就是View的點擊事件黎比,由此可知,view的onClick()回調是在Action_Up事件中被觸發(fā)的腺办。第134行直接返回了true焰手,可以看出只要View處于可點擊狀態(tài),并且進入了switch的判斷邏輯怀喉,就會被返回true书妻,表明該事件被消費掉了,也就是說只要View是可點擊的躬拢,事件傳到了其OnTouchEvent躲履,都會被消費掉。而平時我們在調用setOnClickListener方法給View設置點擊事件監(jiān)聽時聊闯,都會將其點擊狀態(tài)修改為可點擊狀態(tài)工猜。

    public void setOnClickListener(@Nullable OnClickListener l) {
        if (!isClickable()) {
            setClickable(true);
        }
        getListenerInfo().mOnClickListener = l;
    }

追溯完View的事件分發(fā)流程,我們再返回到ViewGroup的dispatchTouchEvent方法的122行菱蔬,如果對應得child消費了點擊事件篷帅,就會通過對應的dispatchTouchEvent方法返回true并最終在122行使得條件成立史侣,然后會進入到138行,調用addTouchTarget對newTouchTarget進行賦值魏身,并且mFirstTouchTarget跟newTouchTarget的值都一樣惊橱,然后將alreadyDispatchedToNewTouchTarget置為true

    private TouchTarget addTouchTarget(View child, int pointerIdBits) {
        TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
        target.next = mFirstTouchTarget;
        mFirstTouchTarget = target;
        return target;
    }

然后來到了163行,由于mFirstTouchTarget和newTouchTarget在addTouchTarget中都被賦值了箭昵,所以會直接進入172行的while循環(huán)税朴,由于之前在138、139行對mFirstTouchTarget家制、newTouchTarget正林、alreadyDispatchedToNewTouchTarget都賦值了,使得174行條件成立颤殴,所以就直接返回true了觅廓,至此,ViewGroup就完成了對子View的遍歷及事件分發(fā)诅病,由于事件被消費掉了哪亿,所以ViewGroup對應的所有外圍容器都會遞歸回調dispatchTouchEvent將true傳遞給Activity,到這也就解釋了測試情景2的產(chǎn)生原理贤笆。在Down相關事件被消費掉之后蝇棉,后續(xù)的Move、Up事件在dispatchTouchEvent方法的68~70行不符合判斷條件芥永,直接會來到179行的dispatchTransformedTouchEvent方法繼續(xù)進行分發(fā)篡殷,待子View進行消費。
如果在ViewGroup的dispatchTouchEvent方法第58行被攔截了(對應測試情景4)埋涧,或者107~108行不成立(對應測試情景3)板辽,或者122行返回false(即子View沒有消費事件,對應測試情景1)棘催,則會直接進入到第163行劲弦,這時mFirstTouchTarget肯定為空,所以會又調用dispatchTransformedTouchEvent方法醇坝,而且傳進去的child為空邑跪,最終就會直接走到dispatchTransformedTouchEvent方法的55行,然后調用super.dispatchTouchEvent呼猪,之后的處理邏輯跟前面調View的dispatchTouchEvent邏輯一樣画畅。
終上所述,整個Android的事件分發(fā)機制可以大致概括成如下的流程圖


PS:以上相關的系統(tǒng)代碼均為Android6.0的系統(tǒng)源碼宋距,整個Android事件分發(fā)機制還算有點復雜轴踱,完全給整明白寫下這篇文章還費了些時間,中間查閱了一些資料谚赎,可能有些地方還存在些理解偏差淫僻,還請大家指出相互學習進步

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末诱篷,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子雳灵,更是在濱河造成了極大的恐慌兴蒸,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,599評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件细办,死亡現(xiàn)場離奇詭異,居然都是意外死亡蕾殴,警方通過查閱死者的電腦和手機笑撞,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,629評論 3 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來钓觉,“玉大人茴肥,你說我怎么就攤上這事〉丛郑” “怎么了瓤狐?”我有些...
    開封第一講書人閱讀 158,084評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長批幌。 經(jīng)常有香客問我础锐,道長,這世上最難降的妖魔是什么荧缘? 我笑而不...
    開封第一講書人閱讀 56,708評論 1 284
  • 正文 為了忘掉前任皆警,我火速辦了婚禮,結果婚禮上截粗,老公的妹妹穿的比我還像新娘信姓。我一直安慰自己,他們只是感情好绸罗,可當我...
    茶點故事閱讀 65,813評論 6 386
  • 文/花漫 我一把揭開白布意推。 她就那樣靜靜地躺著,像睡著了一般珊蟀。 火紅的嫁衣襯著肌膚如雪菊值。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 50,021評論 1 291
  • 那天系洛,我揣著相機與錄音俊性,去河邊找鬼。 笑死描扯,一個胖子當著我的面吹牛定页,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播绽诚,決...
    沈念sama閱讀 39,120評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼典徊,長吁一口氣:“原來是場噩夢啊……” “哼杭煎!你這毒婦竟也來了?” 一聲冷哼從身側響起卒落,我...
    開封第一講書人閱讀 37,866評論 0 268
  • 序言:老撾萬榮一對情侶失蹤羡铲,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后儡毕,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體也切,經(jīng)...
    沈念sama閱讀 44,308評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,633評論 2 327
  • 正文 我和宋清朗相戀三年腰湾,在試婚紗的時候發(fā)現(xiàn)自己被綠了雷恃。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,768評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡费坊,死狀恐怖倒槐,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情附井,我是刑警寧澤讨越,帶...
    沈念sama閱讀 34,461評論 4 333
  • 正文 年R本政府宣布,位于F島的核電站永毅,受9級特大地震影響把跨,放射性物質發(fā)生泄漏。R本人自食惡果不足惜沼死,卻給世界環(huán)境...
    茶點故事閱讀 40,094評論 3 317
  • 文/蒙蒙 一节猿、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧漫雕,春花似錦滨嘱、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,850評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至魁蒜,卻和暖如春囊扳,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背兜看。 一陣腳步聲響...
    開封第一講書人閱讀 32,082評論 1 267
  • 我被黑心中介騙來泰國打工锥咸, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人细移。 一個月前我還...
    沈念sama閱讀 46,571評論 2 362
  • 正文 我出身青樓搏予,卻偏偏與公主長得像,于是被迫代替她去往敵國和親弧轧。 傳聞我的和親對象是個殘疾皇子雪侥,可洞房花燭夜當晚...
    茶點故事閱讀 43,666評論 2 350

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