Android事件分發(fā)機(jī)制

<h1 align = "center">Android事件分發(fā)機(jī)制</h1>


前言:網(wǎng)上有很多關(guān)于Android事件分發(fā)的文章,但大多是基于使用經(jīng)驗(yàn)或者Log來總結(jié)出來的,本文主要從源碼進(jìn)行分析,徹底了解Android事件分發(fā)的原理。以下的內(nèi)容都是基于Android7.1源碼的。

Activity的事件分發(fā)機(jī)制

一般情況下,對(duì)于應(yīng)用層來說,事件的分發(fā)是從Activity接收到來自系統(tǒng)的TouchEvent開始的。Activity的dispatchTouchEvent首先被調(diào)用:

public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        // 可以重寫這個(gè)方法,處理ACTION_DOWN事件,可以看出,任何事件序列都會(huì)首先調(diào)用這個(gè)函數(shù),如果需要監(jiān)聽用戶是否觸摸屏幕,那么建議重寫這個(gè)函數(shù)即可。
        onUserInteraction();
    }
    // 將事件交由Window處理,返回true表示事件已經(jīng)消耗掉了,于是返回true告訴系統(tǒng)。
    if (getWindow().superDispatchTouchEvent(ev)) {
        return true;
    }
    // 如果該事件沒有被Window消耗掉,那么Activity的TouchEvent將會(huì)被調(diào)用。
    return onTouchEvent(ev);
}

Activity的事件分發(fā)比較簡(jiǎn)單,由源碼可以看出,如果Window消耗了事件,或者Activity自身的onTouchEvent消耗了事件,都將會(huì)返回true,告訴系統(tǒng)事件已經(jīng)被消耗掉。

我們知道,一個(gè)事件序列基本都是由ACTION_DOWN,ACTION_MOVE...,ACTION_MOVE,ACTION_UP構(gòu)成的,在Activity的事件分發(fā)機(jī)制里面,一個(gè)事件序列里面的每個(gè)子事件的處理都是獨(dú)立開來的,即,就算Activity不消耗ACTION_DOWN事件,接下來的ACTION_MOVE,ACTION_UP等事件都會(huì)繼續(xù)傳遞給Activity處理。

Window的事件分發(fā)機(jī)制

在事件分發(fā)的過程中,Window只是作為中間的橋梁,這里沒什么好說的。直接源碼:

// 這個(gè)函數(shù)是在PhoneWindow里面的,實(shí)際上Activity中的Window,就是一個(gè)PhoneWindow
public boolean superDispatchTouchEvent(MotionEvent event) {
        // 直接交由DecorView處理
        return mDecor.superDispatchTouchEvent(event);
}

ViewGroup的事件分發(fā)機(jī)制

查看DecorView的源碼發(fā)現(xiàn),實(shí)際上,就是間接調(diào)用ViewGroup的dispatchTouchEvent,因?yàn)镈ecorView繼承自FrameLayout,F(xiàn)rameLayout繼承自ViewGroup,F(xiàn)rameLayout并沒有重寫dispatchTouchEvent函數(shù),所以最終調(diào)用的是ViewGroup的dispatchTouchEvent。

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

下面是把一些無關(guān)的代碼刪除后,ViewGroup的dispatchTouchEvent的實(shí)現(xiàn),每一事件序列都維護(hù)著一個(gè)觸摸鏈表,觸摸鏈表的節(jié)點(diǎn)實(shí)體是TouchTarget,
事件序列中的任一事件,將會(huì)更新觸摸鏈表。觸摸鏈表是當(dāng)前觸點(diǎn)可以觸摸到的子View的集合,例如一個(gè)ViewGroup中有2個(gè)子View,A和B,A和B有重合的部分,
如果手指觸摸到重合的部分,那么觸摸鏈表里面就是A和B,如果只是觸摸到A獨(dú)有的部分,那么觸摸鏈表就是只有A。

public boolean dispatchTouchEvent(MotionEvent ev) {

    boolean handled = false;
    // 過濾一些不安全的觸摸事件,比如當(dāng)前View被別的可見分Window遮擋住了。
    if (onFilterTouchEventForSecurity(ev)) {
        final int action = ev.getAction();
        final int actionMasked = action & MotionEvent.ACTION_MASK;

        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // 清除之前的事件序列狀態(tài),另外,如果上一個(gè)事件序列結(jié)束后,當(dāng)前這個(gè)ViewGroup被設(shè)置成不攔截事件的,
            // 那么在這個(gè)事件開始時(shí),總是被設(shè)置成可以攔截事件。即設(shè)置FLAG_DISALLOW_INTERCEPT只是在一個(gè)事件序列內(nèi)有效。
            // mFirstTouchTarget也會(huì)被清除。
            cancelAndClearTouchTargets(ev);
            resetTouchState();
        }

        // Check for interception.
        final boolean intercepted;
        // 一般情況下,如果是ACTION_DOWN事件,那么mFirstTouchTarget就為null,因?yàn)樵谏厦娴拇a里面,ACTION_DOWN事件將會(huì)首先清除觸摸鏈表
        // 如果不是ACTION_DOWN,而這個(gè)時(shí)候mFirstTouchTarget不為null,那么說明,ACTION_DOWN事件已經(jīng)被當(dāng)前ViewGroup的某一個(gè)子View消耗了
        // 于是會(huì)繼續(xù)嘗試攔截,于是可以得出:ViewGroup可以在事件序列的任一個(gè)節(jié)點(diǎn)阻止事件繼續(xù)往下傳遞。
        if (actionMasked == MotionEvent.ACTION_DOWN
                || mFirstTouchTarget != null) {
            // 是否允許攔截事件,記住,F(xiàn)LAG_DISALLOW_INTERCEPT會(huì)在ACTION_DOWN事件到來時(shí)被重設(shè),所以,
            // onInterceptTouchEvent 總是會(huì)被調(diào)用(ACTION_DOWN事件)
            final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
            if (!disallowIntercept) {
                // 我們可以重寫ViewGroup的onInterceptTouchEvent來決定要不要攔截事件
                intercepted = onInterceptTouchEvent(ev);
                ev.setAction(action); // restore action in case it was changed
            } else {
                intercepted = false;
            }
        } else {
            // 如果不是ACTION_DOWN,而這個(gè)時(shí)候mFirstTouchTarget又為null,那么說明ACTION_DOWN事件已經(jīng)被當(dāng)前的ViewGroup攔截了,或者是
            // 沒有子View消耗ACTION_DOWN事件,
            // 于是,當(dāng)前ViewGroup應(yīng)該繼續(xù)攔截接下來的一個(gè)事件序列內(nèi)的所有事件。
            intercepted = true;
        }

        // 如果事件被攔截了,或者有子View處理了,都進(jìn)行正常的分發(fā)。
        if (intercepted || mFirstTouchTarget != null) {
            ev.setTargetAccessibilityFocus(false);
        }

        // 檢查該事件是否應(yīng)該取消。
        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 = buildTouchDispatchChildList();
                    final boolean customOrder = preorderedList == null
                            && isChildrenDrawingOrderEnabled();
                    final View[] children = mChildren;
                    // 遍歷所有子View,并將事件分發(fā)給子View(如果該子View能接受事件的話)。
                    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;
                        }
                        // View如果不可見,或者事件坐標(biāo)不在View范圍內(nèi),那么View不能處理該事件。
                        if (!canViewReceivePointerEvents(child)
                                || !isTransformedTouchPointInView(x, y, child, null)) {
                            ev.setTargetAccessibilityFocus(false);
                            continue;
                        }

                        // 執(zhí)行到這里的時(shí)候,說明View是具有響應(yīng)當(dāng)前事件的能力的(看上面的if語句)
                        // 假設(shè)當(dāng)前事件不是DOWN事件,那么View應(yīng)該就在觸摸鏈表中了,即newTouchTarget不為null,
                        // 于是將會(huì)跳出循環(huán)
                        // 例外的情況是:如果是滑動(dòng)的時(shí)候,滑到了一個(gè)全新的子View中,newTouchTarget == null,那么就會(huì)跑下面的代碼
                        // 將該子View加入到觸摸鏈表中。
                        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);
                        // 將事件傳遞給子View,子View的dispatchTouchEvent被調(diào)用
                        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();
                            // 這個(gè)子view不再觸摸鏈表中,但是其能夠響應(yīng)當(dāng)前的事件,所以理應(yīng)將它加入到觸摸鏈表中。
                            // 將該子View插入到觸摸目標(biāo)的鏈表頭部。
                            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();
                }

                // 如果沒有找到消耗當(dāng)前事件的子View,那么最新的觸摸目標(biāo)指向最遲最近的的觸摸目標(biāo)
                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) {
            // mFirstTouchTarget == null 說明觸摸鏈表是空的,表示ViewGroup中沒有子View響應(yīng)該事件,那么
            // ViewGroup被當(dāng)做是View對(duì)待,即ViewGroup的父類的dispatchTouchEvent被調(diào)用。ViewGroup的父類是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;
            // 遍歷觸摸鏈表,一個(gè)一個(gè)分發(fā)給鏈表中的view。
            while (target != null) {
                final TouchTarget next = target.next;
                if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                    // 如果分發(fā)過了,那么就不再重復(fù)分發(fā)了
                    handled = true;
                } else {
                    final boolean cancelChild = resetCancelNextUpFlag(target.child)
                            || intercepted;
                    // 分發(fā)給鏈表中的view
                    if (dispatchTransformedTouchEvent(ev, cancelChild,
                            target.child, target.pointerIdBits)) {
                        handled = true;
                    }
                    // 因?yàn)橛|摸點(diǎn)是不停變化的,那么觸摸鏈表也在不停變化,
                    // 對(duì)于一些不再能夠響應(yīng)事件的鏈表節(jié)點(diǎn),將它從鏈表中移除。
                    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;
}

View的事件分發(fā)機(jī)制

View的事件分發(fā)比較簡(jiǎn)單,如果有設(shè)置onTouchListener,那么onTouchListener首先響應(yīng)事件,
onTouchListener 如果不消耗事件,那么輪到onTouchEvent響應(yīng)事件,如果連onTouchEvent都不消耗事件,
那么表明該View不消耗事件,返回false,將事件交由父View處理。

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

    // 如果當(dāng)前View被別的可見的Window遮擋,那么無法響應(yīng)事件
    // 例如Toast
    if (onFilterTouchEventForSecurity(event)) {
        if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
            result = true;
        }
        //noinspection SimplifiableIfStatement
        ListenerInfo li = mListenerInfo;
        // 如果View有設(shè)置OnTouchListener,那么OnTouchListener首先響應(yīng)事件。
        if (li != null && li.mOnTouchListener != null
                && (mViewFlags & ENABLED_MASK) == ENABLED
                && li.mOnTouchListener.onTouch(this, event)) {
            result = true;
        }

        // 如果OnTouchListener不響應(yīng)事件,那么輪到onTouchEvent響應(yīng)事件
        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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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