1. 程式人生 > >Android事件分發機制完全解析,帶你從原始碼的角度徹底理解(下) (出自郭林老師)

Android事件分發機制完全解析,帶你從原始碼的角度徹底理解(下) (出自郭林老師)

記得在前面的文章中,我帶大家一起從原始碼的角度分析了Android中View的事件分發機制,相信閱讀過的朋友對View的事件分發已經有比較深刻的理解了。

那麼今天我們將繼續上次未完成的話題,從原始碼的角度分析ViewGroup的事件分發。

首先我們來探討一下,什麼是ViewGroup?它和普通的View有什麼區別?

顧名思義,ViewGroup就是一組View的集合,它包含很多的子View和子VewGroup,是Android中所有佈局的父類或間接父類,像LinearLayout、RelativeLayout等都是繼承自ViewGroup的。但ViewGroup實際上也是一個View,只不過比起View,它多了可以包含子View和定義佈局引數的功能。ViewGroup繼承結構示意圖如下所示:


可以看到,我們平時專案裡經常用到的各種佈局,全都屬於ViewGroup的子類。

簡單介紹完了ViewGroup,我們現在通過一個Demo來演示一下Android中VewGroup的事件分發流程吧。

首先我們來自定義一個佈局,命名為MyLayout,繼承自LinearLayout,如下所示:

  1. publicclass MyLayout extends LinearLayout {  
  2.     public MyLayout(Context context, AttributeSet attrs) {  
  3.         super(context, attrs);  
  4.     }  
  5. }  

然後,開啟主佈局檔案activity_main.xml,在其中加入我們自定義的佈局:

  1. <com.example.viewgrouptouchevent.MyLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  2.     xmlns:tools="http://schemas.android.com/tools"
  3.     android:id="@+id/my_layout"
  4.     android:layout_width="match_parent"
  5.     android:layout_height="match_parent"
  6.     android:orientation
    ="vertical">
  7.     <Button
  8.         android:id="@+id/button1"
  9.         android:layout_width="match_parent"
  10.         android:layout_height="wrap_content"
  11.         android:text="Button1"/>
  12.     <Button
  13.         android:id="@+id/button2"
  14.         android:layout_width="match_parent"
  15.         android:layout_height="wrap_content"
  16.         android:text="Button2"/>
  17. </com.example.viewgrouptouchevent.MyLayout>
可以看到,我們在MyLayout中添加了兩個按鈕,接著在MainActivity中為這兩個按鈕和MyLayout都註冊了監聽事件:
  1. myLayout.setOnTouchListener(new OnTouchListener() {  
  2.     @Override
  3.     publicboolean onTouch(View v, MotionEvent event) {  
  4.         Log.d("TAG""myLayout on touch");  
  5.         returnfalse;  
  6.     }  
  7. });  
  8. button1.setOnClickListener(new OnClickListener() {  
  9.     @Override
  10.     publicvoid onClick(View v) {  
  11.         Log.d("TAG""You clicked button1");  
  12.     }  
  13. });  
  14. button2.setOnClickListener(new OnClickListener() {  
  15.     @Override
  16.     publicvoid onClick(View v) {  
  17.         Log.d("TAG""You clicked button2");  
  18.     }  
  19. });  

我們在MyLayout的onTouch方法,和Button1、Button2的onClick方法中都列印了一句話。現在執行一下專案,效果圖如下所示:


分別點選一下Button1、Button2和空白區域,列印結果如下所示:


你會發現,當點選按鈕的時候,MyLayout註冊的onTouch方法並不會執行,只有點選空白區域的時候才會執行該方法。你可以先理解成Button的onClick方法將事件消費掉了,因此事件不會再繼續向下傳遞。

那就說明Android中的touch事件是先傳遞到View,再傳遞到ViewGroup的?現在下結論還未免過早了,讓我們再來做一個實驗。

查閱文件可以看到,ViewGroup中有一個onInterceptTouchEvent方法,我們來看一下這個方法的原始碼:

  1. /** 
  2.  * Implement this method to intercept all touch screen motion events.  This 
  3.  * allows you to watch events as they are dispatched to your children, and 
  4.  * take ownership of the current gesture at any point. 
  5.  * 
  6.  * <p>Using this function takes some care, as it has a fairly complicated 
  7.  * interaction with {@link View#onTouchEvent(MotionEvent) 
  8.  * View.onTouchEvent(MotionEvent)}, and using it requires implementing 
  9.  * that method as well as this one in the correct way.  Events will be 
  10.  * received in the following order: 
  11.  * 
  12.  * <ol> 
  13.  * <li> You will receive the down event here. 
  14.  * <li> The down event will be handled either by a child of this view 
  15.  * group, or given to your own onTouchEvent() method to handle; this means 
  16.  * you should implement onTouchEvent() to return true, so you will 
  17.  * continue to see the rest of the gesture (instead of looking for 
  18.  * a parent view to handle it).  Also, by returning true from 
  19.  * onTouchEvent(), you will not receive any following 
  20.  * events in onInterceptTouchEvent() and all touch processing must 
  21.  * happen in onTouchEvent() like normal. 
  22.  * <li> For as long as you return false from this function, each following 
  23.  * event (up to and including the final up) will be delivered first here 
  24.  * and then to the target's onTouchEvent(). 
  25.  * <li> If you return true from here, you will not receive any 
  26.  * following events: the target view will receive the same event but 
  27.  * with the action {@link MotionEvent#ACTION_CANCEL}, and all further 
  28.  * events will be delivered to your onTouchEvent() method and no longer 
  29.  * appear here. 
  30.  * </ol> 
  31.  * 
  32.  * @param ev The motion event being dispatched down the hierarchy. 
  33.  * @return Return true to steal motion events from the children and have 
  34.  * them dispatched to this ViewGroup through onTouchEvent(). 
  35.  * The current target will receive an ACTION_CANCEL event, and no further 
  36.  * messages will be delivered here. 
  37.  */
  38. publicboolean onInterceptTouchEvent(MotionEvent ev) {  
  39.     returnfalse;  
  40. }  

如果不看原始碼你還真可能被這注釋嚇到了,這麼長的英文註釋看得頭都大了。可是原始碼竟然如此簡單!只有一行程式碼,返回了一個false!

好吧,既然是布林型的返回,那麼只有兩種可能,我們在MyLayout中重寫這個方法,然後返回一個true試試,程式碼如下所示:

  1. publicclass MyLayout extends LinearLayout {  
  2.     public MyLayout(Context context, AttributeSet attrs) {  
  3.         super(context, attrs);  
  4.     }  
  5.     @Override
  6.     publicboolean onInterceptTouchEvent(MotionEvent ev) {  
  7.         returntrue;  
  8.     }  
  9. }  

現在再次執行專案,然後分別Button1、Button2和空白區域,列印結果如下所示:


你會發現,不管你點選哪裡,永遠都只會觸發MyLayout的touch事件了,按鈕的點選事件完全被遮蔽掉了!這是為什麼呢?如果Android中的touch事件是先傳遞到View,再傳遞到ViewGroup的,那麼MyLayout又怎麼可能遮蔽掉Button的點選事件呢?

看來只有通過閱讀原始碼,搞清楚Android中ViewGroup的事件分發機制,才能解決我們心中的疑惑了,不過這裡我想先跟你透露一句,Android中touch事件的傳遞,絕對是先傳遞到ViewGroup,再傳遞到View的。記得在Android事件分發機制完全解析,帶你從原始碼的角度徹底理解(上) 中我有說明過,只要你觸摸了任何控制元件,就一定會呼叫該控制元件的dispatchTouchEvent方法。這個說法沒錯,只不過還不完整而已。實際情況是,當你點選了某個控制元件,首先會去呼叫該控制元件所在佈局的dispatchTouchEvent方法,然後在佈局的dispatchTouchEvent方法中找到被點選的相應控制元件,再去呼叫該控制元件的dispatchTouchEvent方法。如果我們點選了MyLayout中的按鈕,會先去呼叫MyLayout的dispatchTouchEvent方法,可是你會發現MyLayout中並沒有這個方法。那就再到它的父類LinearLayout中找一找,發現也沒有這個方法。那隻好繼續再找LinearLayout的父類ViewGroup,你終於在ViewGroup中看到了這個方法,按鈕的dispatchTouchEvent方法就是在這裡呼叫的。修改後的示意圖如下所示:


那還等什麼?快去看一看ViewGroup中的dispatchTouchEvent方法的原始碼吧!程式碼如下所示:

  1. publicboolean dispatchTouchEvent(MotionEvent ev) {  
  2.     finalint action = ev.getAction();  
  3.     finalfloat xf = ev.getX();  
  4.     finalfloat yf = ev.getY();  
  5.     finalfloat scrolledXFloat = xf + mScrollX;  
  6.     finalfloat scrolledYFloat = yf + mScrollY;  
  7.     final Rect frame = mTempRect;  
  8.     boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;  
  9.     if (action == MotionEvent.ACTION_DOWN) {  
  10.         if (mMotionTarget != null) {  
  11.             mMotionTarget = null;  
  12.         }  
  13.         if (disallowIntercept || !onInterceptTouchEvent(ev)) {  
  14.             ev.setAction(MotionEvent.ACTION_DOWN);  
  15.             finalint scrolledXInt = (int) scrolledXFloat;  
  16.             finalint scrolledYInt = (int) scrolledYFloat;  
  17.             final View[] children = mChildren;  
  18.             finalint count = mChildrenCount;  
  19.             for (int i = count - 1; i >= 0; i--) {  
  20.                 final View child = children[i];  
  21.                 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE  
  22.                         || child.getAnimation() != null) {  
  23.                     child.getHitRect(frame);  
  24.                     if (frame.contains(scrolledXInt, scrolledYInt)) {  
  25.                         finalfloat xc = scrolledXFloat - child.mLeft;  
  26.                         finalfloat yc = scrolledYFloat - child.mTop;  
  27.                         ev.setLocation(xc, yc);  
  28.                         child.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  
  29.                         if (child.dispatchTouchEvent(ev))  {  
  30.                             mMotionTarget = child;  
  31.                             returntrue;  
  32.                         }  
  33.                     }  
  34.                 }  
  35.             }  
  36.         }  
  37.     }  
  38.     boolean isUpOrCancel = (action == MotionEvent.ACTION_UP) ||  
  39.             (action == MotionEvent.ACTION_CANCEL);  
  40.     if (isUpOrCancel) {  
  41.         mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;  
  42.     }  
  43.     final View target = mMotionTarget;  
  44.     if (target == null) {  
  45.         ev.setLocation(xf, yf);  
  46.         if ((mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {  
  47.             ev.setAction(MotionEvent.ACTION_CANCEL);  
  48.             mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  
  49.         }  
  50.         returnsuper.dispatchTouchEvent(ev);  
  51.     }  
  52.     if (!disallowIntercept && onInterceptTouchEvent(ev)) {  
  53.         finalfloat xc = scrolledXFloat - (float) target.mLeft;  
  54.         finalfloat yc = scrolledYFloat - (float) target.mTop;  
  55.         mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  
  56.         ev.setAction(MotionEvent.ACTION_CANCEL);  
  57.         ev.setLocation(xc, yc);  
  58.         if (!target.dispatchTouchEvent(ev)) {  
  59.         }  
  60.         mMotionTarget = null;  
  61.         returntrue;  
  62.     }  
  63.     if (isUpOrCancel) {  
  64.         mMotionTarget = null;  
  65.     }  
  66.     finalfloat xc = scrolledXFloat - (float) target.mLeft;  
  67.     finalfloat yc = scrolledYFloat - (float) target.mTop;  
  68.     ev.setLocation(xc, yc);  
  69.     if ((target.mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {  
  70.         ev.setAction(MotionEvent.ACTION_CANCEL);  
  71.         target.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  
  72.         mMotionTarget = null;  
  73.     }  
  74.     return target.dispatchTouchEvent(ev);  
  75. }  

這個方法程式碼比較長,我們只挑重點看。首先在第13行可以看到一個條件判斷,如果disallowIntercept和!onInterceptTouchEvent(ev)兩者有一個為true,就會進入到這個條件判斷中。disallowIntercept是指是否禁用掉事件攔截的功能,預設是false,也可以通過呼叫requestDisallowInterceptTouchEvent方法對這個值進行修改。那麼當第一個值為false的時候就會完全依賴第二個值來決定是否可以進入到條件判斷的內部,第二個值是什麼呢?竟然就是對onInterceptTouchEvent方法的返回值取反!也就是說如果我們在onInterceptTouchEvent方法中返回false,就會讓第二個值為true,從而進入到條件判斷的內部,如果我們在onInterceptTouchEvent方法中返回true,就會讓第二個值為false,從而跳出了這個條件判斷。

這個時候你就可以思考一下了,由於我們剛剛在MyLayout中重寫了onInterceptTouchEvent方法,讓這個方法返回true,導致所有按鈕的點選事件都被遮蔽了,那我們就完全有理由相信,按鈕點選事件的處理就是在第13行條件判斷的內部進行的!

那我們重點來看下條件判斷的內部是怎麼實現的。在第19行通過一個for迴圈,遍歷了當前ViewGroup下的所有子View,然後在第24行判斷當前遍歷的View是不是正在點選的View,如果是的話就會進入到該條件判斷的內部,然後在第29行呼叫了該View的dispatchTouchEvent,之後的流程就和 Android事件分發機制完全解析,帶你從原始碼的角度徹底理解(上) 中講解的是一樣的了。我們也因此證實了,按鈕點選事件的處理確實就是在這裡進行的。

然後需要注意一下,呼叫子View的dispatchTouchEvent後是有返回值的。我們已經知道,如果一個控制元件是可點選的,那麼點選該控制元件時,dispatchTouchEvent的返回值必定是true。因此會導致第29行的條件判斷成立,於是在第31行給ViewGroup的dispatchTouchEvent方法直接返回了true。這樣就導致後面的程式碼無法執行到了,也是印證了我們前面的Demo列印的結果,如果按鈕的點選事件得到執行,就會把MyLayout的touch事件攔截掉。

那如果我們點選的不是按鈕,而是空白區域呢?這種情況就一定不會在第31行返回true了,而是會繼續執行後面的程式碼。那我們繼續往後看,在第44行,如果target等於null,就會進入到該條件判斷內部,這裡一般情況下target都會是null,因此會在第50行呼叫super.dispatchTouchEvent(ev)。這句程式碼會呼叫到哪裡呢?當然是View中的dispatchTouchEvent方法了,因為ViewGroup的父類就是View。之後的處理邏輯又和前面所說的是一樣的了,也因此MyLayout中註冊的onTouch方法會得到執行。之後的程式碼在一般情況下是走不到的了,我們也就不再繼續往下分析。

再看一下整個ViewGroup事件分發過程的流程圖吧,相信可以幫助大家更好地去理解:


現在整個ViewGroup的事件分發流程的分析也就到此結束了,我們最後再來簡單梳理一下吧。

1. Android事件分發是先傳遞到ViewGroup,再由ViewGroup傳遞到View的。

2. 在ViewGroup中可以通過onInterceptTouchEvent方法對事件傳遞進行攔截,onInterceptTouchEvent方法返回true代表不允許事件繼續向子View傳遞,返回false代表不對事件進行攔截,預設返回false。

3. 子View中如果將傳遞的事件消費掉,ViewGroup中將無法接收到任何事件。

好了,Android事件分發機制完全解析到此全部結束,結合上下兩篇,相信大家對事件分發的理解已經非常深刻了。