事件分發機制(二):源碼篇

上篇對總體事件分發流程大體梳理下,有興趣的朋友能夠去看看事件分發機制(一):解惑篇java

本篇就基於上篇的知識上,跟着你們走一波事件分發的源碼,這樣可能你們可以更理解下源碼.ide

Acitvity ## dispatchTouchEvent

事件源頭從Activity向下進行分發,點進查看看dispatchTouchEvent代碼post

public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        //具體的工做由 Activity 內部的 Window 來完成的。若是返回 true,整個事件循環就結束了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        //若是下面的都沒有給消費掉,最後事件只能有本身onTouchEvent消費了
        return onTouchEvent(ev);
    }
複製代碼

代碼比較簡單,事件從Activity向下分發,若是事件被消費,直接返回True,若是都沒有處理消費,只能由本身onTouchEvent本身處理,因而可知,總體事件分發機制就是相似一個U字型的流程,事件由Activity開始分發,到最底層的View,最後回到Activity的onTouchEvent,固然,這之間任何一個地方返回True都可以打斷這個流程。this

PhoneWindow ## superDispatchTouchEvent

惟一實現Window類的就是PhoneWindow類,因此實際上就是調用PhoneWindow的方法了spa

@Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);
    }
複製代碼

PhoneWindow將事件直接傳遞給了 DecorView,熟悉setContentView代碼的朋友應該知道,DecorView實際上就是而咱們經過 setContentView設置的 View,因此事件最終也是走進了ViewGroup中code

ViewGroup ## dispatchTouchEvent

/ ViewGroup.java

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
            ...
        
            // Check for interception.
            final boolean intercepted;
            //若是是ACTION_DOWN,重置mFirstTouchTarget以及FLAG_DISALLOW_INTERCEPT標誌位
            if (actionMasked == MotionEvent.ACTION_DOWN) {            
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }
            //這裏2個條件,知足1個便可進入判斷體內
            //1.當前的事件行爲爲MotionEvent.ACTION_DOWN
            //2.mFirstTouchTarget對象不爲空,這個對象能夠理解爲當事件由ViewGroup的子元素處理時,那麼mFirstTouchTarget指向那個子元素
            if (actionMasked == MotionEven_ACTION_DOWN
                    || mFirstTouchTarget != null) { 
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                   intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); 
                } else {
                    intercepted = false;
                }
            } else {
                intercepted = true;
            }
            
            ...
    }
複製代碼

代碼比較長,咱們看關鍵代碼,首先第一個判斷,若是當前事件狀態爲ACTION_DOWN,則重置mFirstTouchTarget置位空,以及將FLAG_DISALLOW_INTERCEPT重置。orm

  • 咱們應該還記得,子View能夠經過requestDisallowInterceptTouchEvent方法來要求父ViewGroup不攔截事件,實際上就是改變父ViewGroup這裏的這個FLAG_DISALLOW_INTERCEPT標誌位,可是每次DOWN事件這個標誌位會被重置,因此能夠得出結論,當這個標誌位被requestDisallowInterceptTouchEvent改變後,ViewGroup將沒法攔截除了ACTION_DOWN之外的其它點擊事件
  • 當事件被攔截以後,上述mFirstTouchTarget解釋能夠看到,此時mFirstTouchTarget是爲空,因此mFirstTouchTarget!=null是不成立的,此時直接intercepted 爲True,此處也是驗證了上篇的結論,一旦當前View攔截事件,那麼同一事件序列的其它事件都再也不進行攔截校驗,直接交給它處理
  • 對應DOWN事件,ViewGroup每次詢問本身的onInterceptTouchEvent方法,是否須要攔截事件

那麼這裏就分爲兩種狀況了,第一種,首先intercepted爲True,也就是ViewGroup進行攔截處理對象

// 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 {
	...
}
複製代碼

進去方法裏看看事件

private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,View child, int desiredPointerIdBits) {  
    	    .....
            if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else {
                handled = child.dispatchTouchEvent(event);
            }
            event.setAction(oldAction);
            return handled;
       
    }
複製代碼

能夠看到,由於方法是根據傳進的child的值來進行不一樣的操做,這裏由於傳進來的爲null,因此執行super.dispatchTouchEvent(event),因此這裏其實想ViewGroup要處理本身事件,就調用父類View的dispatchTouchEvent()方法,把本身當作一個View來處理這些事件,因此這裏調用了super.dispatchTouchEvent(event),至於View的dispatchTouchEvent()事件怎麼處理的,後面會分析到。ci

第兩者,若是intercepted爲false,貼出部分代碼

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 (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;
    }
    ev.setTargetAccessibilityFocus(false);
}
複製代碼

代碼比較長,主要總結下,遍歷ViewGroup的全部元素,若是觸摸的事件落在遍歷到的view,而且當前遍歷到的元素是能夠接受到這個事件的,知足這兩個條件,這個元素才能接收到父元素傳遞給他的事件。若兩個條件有一個不知足就continue

最終能夠看到仍是走到了dispatchTouchEvent方法,不過這裏回傳進去child值,以前也看到過這個方法了,若是child不爲空的話,會調用child的dispatchTouchEvent方法,也就是事件從ViewGroup會傳遞到View中了。

.....
            if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else {
                handled = child.dispatchTouchEvent(event);
            }
複製代碼

View##dispatchTouchEvent

終於到了View中的dispatchTouchEvent,打開方法看看

public boolean dispatchTouchEvent(MotionEvent event) {
...		
      boolean result = false;
...
      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;
          }
      }
...
      return result;
  }

複製代碼

能夠看到mOnTouchListener的優先級是高於onTouchEvent的,若是mOnTouchListener不爲空,而且複寫onTouch方法返回true的話,那麼**!result就爲false了,此時onTouchEvent(event)就不會執行了,若onTouch返回false,onTouchEvent(event)會執行獲得**,這樣能夠在外部控制處理事件

View##onTouchEvent

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) {
				
				...
                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();
                        }
                    }
                }
				...
            }
			...
            break;
    }
    return true;
}
複製代碼

能夠看到,主要走進了這個循環,那麼最終是必定返回true的,也就是隻要View的CLICKABLE和LONG CLICKABLE有一個位true,那麼它就必定會消費這個事件,由於ontouchEvent是返回了true的,而後再ACTION_UP中,會執行performClick,看看這個方法

public boolean performClick() {
        // We still need to call this method to handle the cases where performClick() was called
        // externally, instead of through performClickInternal()
        notifyAutofillManagerOnClick();

        final boolean result;
        final ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnClickListener != null) {
            playSoundEffect(SoundEffectConstants.CLICK);
            li.mOnClickListener.onClick(this);
            result = true;
        } else {
            result = false;
        }
        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);

        notifyEnterOrExitForAutoFillIfNeeded(true);

        return result;
    }
複製代碼

是否是恍然大悟,能夠看到,若是咱們設置的mOnClickListener不爲空的話,那麼這裏會回調onClick方法,也就回調到日常寫的onclik方法之中了。

因此事件執行的順序是DOWN-->MOVE-->UP-->ONCLICK,這裏須要注意的一點是,LongClick的執行順序也是優先於onclick的,若是LongClick的返回位True,也表明着由它消費了這個事件,這個時候onclick也是不會執行的,這個日常在開發的時候須要注意下

好了,大概就是這麼多了,有興趣的朋友能夠兩篇文章結合的一塊兒看下,但願可以幫助到某些朋友一二吧,謝謝!

相關文章
相關標籤/搜索