Android的進(jìn)階學(xué)習(xí)(六)--理解View事件分發(fā)

有些無奈,期末考試抱佛腳,還好沒有掛,現(xiàn)在繼續(xù)進(jìn)階。

好久以前就看到了View的事件分發(fā),但是當(dāng)時功底不夠,源碼也不敢深究,也就是個模模糊糊過了,現(xiàn)在在看一面,才發(fā)現(xiàn)以前許多理解都是錯的,也怪不得當(dāng)時自己都沒有真正弄清楚。


理解之前####

首先我們應(yīng)該明白的是,當(dāng)我們一個觸摸事件來的時候,它是被包裝成的一個MotionEvent,其中就包含了這個事件是 downmoveup其中的一種,還有這個觸摸發(fā)生的地點(diǎn)(也就是坐標(biāo))等等。
其次,我們還需要知道的是,每一次的觸摸事件都是最先把MotionEvent發(fā)送到ActivitydispatchTouchEvent方法中的。
有這兩點(diǎn)基礎(chǔ),我們就可以去探索源碼了。

源碼探索####

既然我們現(xiàn)在已經(jīng)知道了,一個觸摸事件最先就是包裝成一個MotionEvent給發(fā)送到ActivitydispatchTounchEvent了,那么我們當(dāng)然從這個方法看起走呀。

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

在這個方法中,傳遞了一個MotionEvent作為參數(shù),也就是我們的觸摸事件傳遞給了這個方法。然后進(jìn)行了一點(diǎn)簡單的邏輯,首先判斷一下MotionEvent是否為down,如果是的話就調(diào)用 onUserInteraction()。而onUserInteraction()就是一個空方法,目的就是實現(xiàn)這個方法,可以更加方便管理一些notfication

public void onUserInteraction() { }
所以和我們的事件分發(fā)并沒有很大的關(guān)系,重要的是下面的幾句。
這里調(diào)用了Activity所對應(yīng)的WindowsuperDispatchTouchEvent(ev)方法來進(jìn)行事件的分發(fā)。然后我們接著尋找這個方法,在Window這個抽象類中發(fā)現(xiàn)了這個抽象方法superDispatchTouchEvent(ev),有這個方法明我們也可以看出來,這里是調(diào)用的Window的實現(xiàn)類的方法啦。
于是我們就可以找到這個Window的唯一實現(xiàn)類PhoneWindow,在這個類中,我們找到了superDispatchTouchEvent(ev)方法。在這個方法中,也是相當(dāng)?shù)暮唵危椭苯诱{(diào)用了mDecor.superDispatchTouchEvent,也就是這句話,我們的事件終于傳到了View了。對,這里的mDecor就是我們ActivitysetContent中所設(shè)置的View的父容器,也就是頂級容器了。

看到了這里,才真正的開始進(jìn)行View的事件分發(fā)了,不過再之前,還是先理一下,以便后面好理解。

  1. MotionEvent現(xiàn)在是傳到Activity的頂級View的,我們的事件分發(fā)就是從這個頂級View向它的子View進(jìn)行分發(fā)的。
  2. 頂級View所包含的子View,子View中又包含子View,形成一個View樹。
  3. 事件分發(fā)就是把事件(MotionEvent) 按照先序遍歷所有節(jié)點(diǎn),直到找到一個View消費(fèi)掉這個事件。所謂的消費(fèi)這個事件,就是相應(yīng)的ViewOntouchListener返回true或者OntouchEvent()返回為true
  4. 事件分發(fā)主要由三個函數(shù)控制,分別是dispatchTouchEvent分發(fā)事件,onInterceptTouchEvent攔截事件,onTouchEvent響應(yīng)事件。
View的事件分發(fā).png

深入分發(fā)####

事件傳到頂級View(ViewGroup)中時,就會調(diào)用dispatchTouchEvent進(jìn)行分發(fā)。

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    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;
        }

看上面的dispatchTouchEvent的邏輯也是很好理解的,首先會判斷我們傳來的TouchEvent是不是down,如果是的話,就會調(diào)用resetTouchSate方法,不過現(xiàn)在我們暫時不需要知道這個方法的具體作用,但是從方法名中我們也能得到一些提示,也就是每當(dāng)遇到down就會重新設(shè)置一些狀態(tài)。
然后,這里就會判斷是否需要調(diào)用onInterceptTouchEvent方法,也就是注釋中的 Check for interception。值得注意的是這里是兩層判斷,也就是有兩個嵌套的if
在第一個if中,會確定觸摸事件是否為downmFirstTouchTarget是不是為空。其中mFirstTouchTarget表示的是事件是不是又子View消費(fèi)了的,如果已經(jīng)被消費(fèi),就不會為null。在第二個if中就會判斷是否設(shè)置了FLAG_DISALLOW_INTERCEPT這個 標(biāo)記符,這個FLAG_DISALLOW_INTERCEPT標(biāo)記符的作用就是子View干涉父容器對事件的分發(fā)。如果子View設(shè)置了這個標(biāo)記符,就不會調(diào)用onInterceptTouchEvent方法,從而intercepted為false。

如果兩層if都滿足,就會調(diào)用onInterceptTouchEvent來對事件進(jìn)行攔截。

接下來,我們就看看如果父容器不攔截,即intercepted為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 
                // 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;
        }
    }}

代碼有點(diǎn)多,不過抓重點(diǎn)看的話也就那幾行。
這里主要是有一個for循環(huán),對子View進(jìn)行了遍歷,然后判斷是否能夠接受觸摸事件,可以接受的話就會調(diào)用dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)MotionEvent給傳給子View,這個方法的返回值就是表示是否消費(fèi)了該事件,也就是OnTouchListener或者OntouchEvent是否返回了true

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

可以看到,這里dispatchTransformedTouchEvent就會讓子View重復(fù)父容器類似的分發(fā)方式。

如果有子View消費(fèi)的話就會跳出for循環(huán),并且在addTouchTarget(child, idBitsToAssign);方法中給前面所說的mFirstTouchTarget賦值。

要是沒有View消費(fèi)該事件或者父容器攔截該事件的話,

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

可以看到,會調(diào)用一個和上面一樣的方法,只是參數(shù)不同而已,因為第三個參數(shù)傳的是null,所以就會調(diào)用super.dispatchTouchEvent(event)方法,這里需要注意的是,這里的super不是父容器,而是指的是本身ViewGroup的父類View的方法,其對象還是這個 ViewGroup

接著我們再考慮一種情況,當(dāng)我們的觸摸事件不為downmFirstTouchTarget != null的話,就會直接在我們TouchTarget中分發(fā)了,也就是 mFirstTouchTarget所保存中進(jìn)行分發(fā)。

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

首先我們要知道的是,TouchTarget是一種單鏈表結(jié)構(gòu),保存了每一次我們不攔截所分發(fā)的View,所以滿足上述情況的時候,就會遍歷這個鏈表進(jìn)行分發(fā)。

上面的所有基本上就是View的事件分發(fā)了,當(dāng)然,當(dāng)一MotionEventViewGroup傳到了View的時候,對應(yīng)的就相當(dāng)簡單了,因為View并沒有子View,而單純的是對于MotionEvent事件的消費(fèi)----OntouchListenerOnTouchEvent的返回值而已,不過值得注意的是OntouchListener的優(yōu)先級比OnTouchEvent,這點(diǎn)從源碼中很輕松就能發(fā)現(xiàn)。

總結(jié)####

View的事件分發(fā) (1).png

最后,還是通過這一張相同的圖進(jìn)行總結(jié)一下。

觸摸事件最初是由Activity傳給Window再傳到頂級View mDercorView中,也就是這里的樹根,然后按照前序遍歷,把觸摸事件向下傳。當(dāng)事件傳到了ViewGroup1的時候,就會遍歷它下面的三個子View,當(dāng)這三個子View都沒有消費(fèi)這個事件的時候,就會調(diào)用ViewGruop1的父類View去試著消費(fèi)這個事件,要是還是沒有被消費(fèi),則ViewGroup2就會重復(fù)ViewGroup1,當(dāng)然,如果ViewGroup2也沒消費(fèi)掉事件(包括它的子View),ViewGroup3還是會繼續(xù)重復(fù)。要是這三個ViewGroup都沒有消費(fèi)掉的話,則又會傳到ViewGroup0的父View去試著消費(fèi),如果也沒有消費(fèi)掉,最后就會傳到Activity中進(jìn)行消費(fèi)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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