從另一個思路來學習安卓事件分發機制
從另一個思路來學習安卓事件分發機制
前言
事件分發機制是一個安卓老生常談的話題了,從前幾年的面試必問題到如今的本當成預設都會的基礎知識。關於這方面的部落格網上已經有很多很多了,有從原始碼分析的,有從實際出發開始分析的等等。面對這麼多的教程,小白可能一頭霧水不知道從哪裡看起,而且看完之後感覺啥也沒留下。那麼我打算從一個全新的角度全新的思路來講解這個問題。
全新的角度
If I have seen further, it is by standing on the shoulders of giants.
站在前輩的肩膀上,我們能看得更遠。所以我們先來看看大佬們已經為我們總結出來的事件分發流程

image
)
從圖上來看我們可以總結出這麼幾個相關方法
public boolean dispatchTouchEvent(MotionEvent ev) {...} public boolean onInterceptTouchEvent(MotionEvent ev) {...} public boolean onTouchEvent(MotionEvent event) {...}
那麼我們就來重點看下這幾個方法:
//首先是Activity中的這個方法 public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { //這是一個空方法,裡面沒有任何邏輯,不會對事件分發造成影響 onUserInteraction(); } //重點是這裡的呼叫Window的superDispatchTouchEvent方法 //具體邏輯中這裡會呼叫的頂級view的dispatchTouchEvent方法 if (getWindow().superDispatchTouchEvent(ev)) { return true; } return onTouchEvent(ev); }
上面的Window中的superDispatchTouchEvent方法的程式碼我就不貼了,我們只要知道他會呼叫Activity中頂級檢視view的dispatchTouchEvent方法。接下來的事件傳遞都在View中了,這部分才是我們需要關心的。
//接著是ViewGroup中的dispatchTouchEvent方法,由於程式碼太多,我們直接看和onInterceptTouchEvent方法有關的部分,應為我們從大佬的部落格中得知ViewGroup裡的dispatchTouchEvent方法中會呼叫onInterceptTouchEvent方法來判斷是否攔截事件. 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); } else { intercepted = false; } } else { intercepted = true; }
從上面程式碼可以看出來當actionMasked為ACTION_DOWN或者mFirstTouchTarget != null時會呼叫onInterceptTouchEvent。那麼這個mFirstTouchTarget到底是個什麼玩意呢?
從後面的程式碼中可以看出這個玩意在 事件被ViewGroup的子元素消費的時候會被複制並指向子元素。
也就是事件被子元素消費後mFirstTouchTarget != null,而當ViewGroup攔截事件時,mFirstTouchTarget為空,所以當接下來的Move和Up一些列事件到來之時,不會再呼叫onInterceptTouchEvent方法,而是直接交由ViewGroup處理。(應為onInterceptTouchEvent不是每次都會被呼叫的,所以我們想處理所有事件是,應該選擇dispatchTouchEvent方法)
說了半天,這個onInterceptTouchEvent看起來這麼重要,那我們就來看下他裡面到底是啥樣的
public boolean onInterceptTouchEvent(MotionEvent ev) { if (ev.isFromSource(InputDevice.SOURCE_MOUSE) && ev.getAction() == MotionEvent.ACTION_DOWN && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY) && isOnScrollbarThumb(ev.getX(), ev.getY())) { return true; } return false; }
可以看到裡面的程式碼很簡單,基本上相當於預設返回false。所以可以總結出ViewGroup中的onInterceptTouchEvent方法預設不攔截事件。
接下來看沒被攔截時會執行的程式碼
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(); }
這段程式碼看著很長,其實邏輯很簡單(不需要讀懂每一行程式碼,大概瞭解思路和執行過程就行)。
遍歷ViewGroup中的所有子元素,判斷子元素是否能夠接受這個事件,如果能夠接受則這個事件會被交給該子元素處理。具體程式碼在這個方法中dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)
if (child == null) { handled = super.dispatchTouchEvent(event); } else { handled = child.dispatchTouchEvent(event); }
如果這個這個child.dispatchTouchEvent(event)方法返回true,代表事件被子view消費,mFirstTouchTarget將會被賦值同時跳出迴圈,如下部分程式碼:
newTouchTarget = addTouchTarget(child, idBitsToAssign); alreadyDispatchedToNewTouchTarget = true; break; //mFirstTouchTarget在此被賦值 private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) { final TouchTarget target = TouchTarget.obtain(child, pointerIdBits); target.next = mFirstTouchTarget; mFirstTouchTarget = target; return target; }
而如果所有子view的dispatchTouchEvent方法都返回false或者沒有子view時,會呼叫如下程式碼
handled = dispatchTransformedTouchEvent(ev, canceled, null, TouchTarget.ALL_POINTER_IDS);
注意這裡傳入的第三個引數也就是child為空,根據上面部分的程式碼來看,當子view為空時會呼叫ViewGroup的父類的dispatchTouchEvent。那麼ViewGroup的部分就到此為止了,接下來是View的部分。
老規矩先來看下View的dispatchTouchEvent方法
//省略了部分無關程式碼,讀者可以自行檢視原始碼 public boolean dispatchTouchEvent(MotionEvent event) { boolean result = false; final int actionMasked = event.getActionMasked(); if (onFilterTouchEventForSecurity(event)) { if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) { result = true; } //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; }
View的dispatchTouchEvent方法比較簡單,程式碼量少了很多。
重點在於這部分程式碼
ListenerInfo li = mListenerInfo; if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && li.mOnTouchListener.onTouch(this, event)) { result = true; }
當li!=null且當li.mOnTouchListener != null的時候會去掉用li.mOnTouchListener.onTouch(this, event)方法。並且當onTouch方法返回為true時,dispatchTouchEvent方法返回true。
那麼什麼時候上訴條件成立呢?
答案是當我們掉用view的setOnTouchListener()方法的時候,而這個onTouch方法就是我們在此設定的。
那麼當我們沒設定該方法或者onTouch返回為false的時候呢?
if (!result && onTouchEvent(event)) { result = true; }
上述程式碼解答了我們問題,當result為false的時候回去呼叫View本身的onTouchEvent方法。所以我們知道onTouch方法會在onTouchEvent之前呼叫,並且能夠在此通過返回true完全消費掉事件使得onTouchEvent方法不會被呼叫。
按照大佬們部落格的說法,當view為可點選時onTouchEvent方法預設返回true表示消費掉了事件,那麼我們就去看看該方法裡面到底是怎麼一回事
//該部分程式碼比較長,刪除了不相關的程式碼,只保留重要部分,讀者可以自行檢視原始碼 public boolean onTouchEvent(MotionEvent event) { final int action = event.getAction(); if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) { switch (action) { case MotionEvent.ACTION_UP: if (mPerformClick == null) { mPerformClick = new PerformClick(); } if (!post(mPerformClick)) { performClick(); } break; } return true; } return false; } //performClick()方法內部 public boolean performClick() { 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; } return result; }
從上面的程式碼可以看出當view可以點選時會呼叫performClick()方法,而這個方法會在li != null && li.mOnClickListener != null時去呼叫onClick方法(也就是我們對view的setOnClickListener方法)。
而不管onClick方法返回什麼,只要view是可點選的onTouchEvent方法都會返回true,看樣子大佬說的一點都沒錯(屁話,大佬還能說錯了?(╯‵□′)╯︵┻━┻)。
那麼這個時候安卓中事件的分發流程好像漸漸清晰了,翻到文章開頭的流程圖,讀者是不是感到已經理解了呢?(如果沒有理解,請拋開部落格,開啟原始碼,對上述的三個方法的原始碼細細看一遍)
尾聲
其實我感覺這篇寫的有點繁瑣和亂,主要還是我功力不夠,雖然自己能夠理解了這部分內容,但是寫的時候總是不能完全表達清楚,有種只可意會不可言傳的感覺。新手朋友可以多參考幾篇部落格,多看幾遍原始碼,一次不行就兩次,兩次不行就三次。世上無難事只怕有心人,只要肯有心總有能學會理解的那一天。
同時安卓新手朋友們可以看看我的另外兩篇部落格分別是關於AsyncTask和SpannableStringBuilder的。