Android源碼分析-對點擊事件派發機制

概述

一直想寫篇關於Android事件派發機制的文章,卻一直沒寫,這兩天剛好是週末,有時間了,想想寫一篇吧,不然總是隻停留在會用的層次上但是無法瞭解其內部機制。我用的是4.4源碼,打開看看,挺複雜的,尤其是事件是怎麼從Activity派發出來的,太費解了。瞭解Windows消息機制的人會發現,覺得Android的事件派發機制和Windows的消息派發機制挺像的,其實這是一種典型的消息“冒泡”機制,很多平臺採用這個機制,消息最先到達最底層View,然後它先進行判斷是不是它所需要的,否則就將消息傳遞給它的子View,這樣一來,消息就從水底的氣泡一樣向上浮了一點距離,以此類推,氣泡達到頂部和空氣接觸,破了(消息被處理了),當然也有氣泡浮出到頂層了,還沒破(消息無人處理),這個消息將由系統來處理,對於Android來說,會由Activity來處理。

Android點擊事件的派發機制

1. 從Activity傳遞到底層View

點擊事件用MotionEvent來表示,當一個點擊操作發生時,事件最先傳遞給當前Activity,由Activity的dispatchTouchEvent來進行事件派發,具體的工作是由Activity內部的Window來完成的,Window會將事件傳遞給decor view,decor view一般就是當前界面的底層容器(即setContentView所設置的View的父容器),通過Activity.getWindow.getDecorView()可以獲得。另外,看下面代碼的的時候,主要看我註釋的地方,代碼很多很複雜,我無法一一說明,但是我註釋的地方都是關鍵點,是博主仔細讀代碼總結出來的。

源碼解讀:

事件是由哪裏傳遞給Activity的,這個我還不清楚,但是不要緊,我們從activity開始分析,已經足夠我們瞭解它的內部實現了。

Code:Activity#dispatchTouchEvent

  1. /** 
  2.  * Called to process touch screen events.  You can override this to 
  3.  * intercept all touch screen events before they are dispatched to the 
  4.  * window.  Be sure to call this implementation for touch screen events 
  5.  * that should be handled normally. 
  6.  *  
  7.  * @param ev The touch screen event. 
  8.  *  
  9.  * @return boolean Return true if this event was consumed. 
  10.  */  
  11. public boolean dispatchTouchEvent(MotionEvent ev) {  
  12.     if (ev.getAction() == MotionEvent.ACTION_DOWN) {  
  13.         //這個函數其實是個空函數,啥也沒幹,如果你沒重寫的話,不用關心  
  14.         onUserInteraction();  
  15.     }  
  16.     //這裏事件開始交給Activity所附屬的Window進行派發,如果返回true,整個事件循環就結束了  
  17.     //返回false意味着事件沒人處理,所有人的onTouchEvent都返回了false,那麼Activity就要來做最後的收場。  
  18.     if (getWindow().superDispatchTouchEvent(ev)) {  
  19.         return true;  
  20.     }  
  21.     //這裏,Activity來收場了,Activity的onTouchEvent被調用  
  22.     return onTouchEvent(ev);  
  23. }  

Window是如何將事件傳遞給ViewGroup的

Code:Window#superDispatchTouchEvent

  1. /** 
  2.  * Used by custom windows, such as Dialog, to pass the touch screen event 
  3.  * further down the view hierarchy. Application developers should 
  4.  * not need to implement or call this. 
  5.  * 
  6.  */  
  7. public abstract boolean superDispatchTouchEvent(MotionEvent event);  
這竟然是一個抽象函數,還註明了應用開發者不要實現它或者調用它,這是什麼情況?再看看如下類的說明,大意是說:這個類可以控制頂級View的外觀和行爲策略,而且還說這個類的唯一一個實現位於android.policy.PhoneWindow,當你要實例化這個Window類的時候,你並不知道它的細節,因爲這個類會被重構,只有一個工廠方法可以使用。好吧,還是很模糊啊,不太懂,不過我們可以看一下android.policy.PhoneWindow這個類,儘管實例化的時候此類會被重構,但是重構而已,功能是類似的。

Abstract base class for a top-level window look and behavior policy. An instance of this class should be used as the top-level view added to the window manager. It provides standard UI policies such as a background, title area, default key processing, etc.

The only existing implementation of this abstract class is android.policy.PhoneWindow, which you should instantiate when needing a Window. Eventually that class will be refactored and a factory method added for creating Window instances without knowing about a particular implementation. 

Code:PhoneWindow#superDispatchTouchEvent
  1. @Override  
  2. public boolean superDispatchTouchEvent(MotionEvent event) {  
  3.     return mDecor.superDispatchTouchEvent(event);  
  4. }  
這個邏輯很清晰了,PhoneWindow將事件傳遞給DecorView了,這個DecorView是啥呢,請看下面
  1. private final class DecorView extends FrameLayout implements RootViewSurfaceTaker  
  2.   
  3. // This is the top-level view of the window, containing the window decor.  
  4. private DecorView mDecor;  
  5.   
  6. @Override  
  7. public final View getDecorView() {  
  8.     if (mDecor == null) {  
  9.         installDecor();  
  10.     }  
  11.     return mDecor;  
  12. }  

順便說一下,平時Window用的最多的就是((ViewGroup)getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0)即通過Activity來得到內部的View。這個mDecor顯然就是getWindow().getDecorView()返回的View,而我們通過setContentView設置的View是它的一個子View。目前事件傳遞到了DecorView 這裏,由於DecorView 繼承自FrameLayout且是我們的父View,所以最終事件會傳遞給我們的View,原因先不管了,換句話來說,事件肯定會傳遞到我們的View,不然我們的應用如何響應點擊事件呢。不過這不是我們的重點,重點是事件到了我們的View以後應該如何傳遞,這是對我們更有用的。從這裏開始,事件已經傳遞到我們的頂級View了,注意:頂級View實際上是最底層View,也叫根View。

2.底層View對事件的分發過程

點擊事件到底層View(一般是一個ViewGroup)以後,會調用ViewGroup的dispatchTouchEvent方法,然後的邏輯是這樣的:如果底層ViewGroup攔截事件即onInterceptTouchEvent返回true,則事件由ViewGroup處理,這個時候,如果ViewGroup的mOnTouchListener被設置,則會onTouch會被調用,否則,onTouchEvent會被調用,也就是說,如果都提供的話,onTouch會屏蔽掉onTouchEvent。在onTouchEvent中,如果設置了mOnClickListener,則onClick會被調用。如果頂層ViewGroup不攔截事件,則事件會傳遞給它的在點擊事件鏈上的子View,這個時候,子View的dispatchTouchEvent會被調用,到此爲止,事件已經從最底層View傳遞給了上一層View,接下來的行爲和其底層View一致,如此循環,完成整個事件派發。另外要說明的是,ViewGroup默認是不攔截點擊事件的,其onInterceptTouchEvent返回false。

源碼解讀:

Code:ViewGroup#dispatchTouchEvent

  1. @Override  
  2. public boolean dispatchTouchEvent(MotionEvent ev) {  
  3.     if (mInputEventConsistencyVerifier != null) {  
  4.         mInputEventConsistencyVerifier.onTouchEvent(ev, 1);  
  5.     }  
  6.   
  7.     boolean handled = false;  
  8.     if (onFilterTouchEventForSecurity(ev)) {  
  9.         final int action = ev.getAction();  
  10.         final int actionMasked = action & MotionEvent.ACTION_MASK;  
  11.   
  12.         // Handle an initial down.  
  13.         if (actionMasked == MotionEvent.ACTION_DOWN) {  
  14.             // Throw away all previous state when starting a new touch gesture.  
  15.             // The framework may have dropped the up or cancel event for the previous gesture  
  16.             // due to an app switch, ANR, or some other state change.  
  17.             cancelAndClearTouchTargets(ev);  
  18.             resetTouchState();  
  19.         }  
  20.   
  21.         // Check for interception.  
  22.         final boolean intercepted;  
  23.         if (actionMasked == MotionEvent.ACTION_DOWN  
  24.                 || mFirstTouchTarget != null) {  
  25.             final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;  
  26.             if (!disallowIntercept) {  
  27.           //這裏判斷是否攔截點擊事件,如果攔截,則intercepted=true  
  28.                 intercepted = onInterceptTouchEvent(ev);  
  29.                 ev.setAction(action); // restore action in case it was changed  
  30.             } else {  
  31.                 intercepted = false;  
  32.             }  
  33.         } else {  
  34.             // There are no touch targets and this action is not an initial down  
  35.             // so this view group continues to intercept touches.  
  36.             intercepted = true;  
  37.         }  
  38.   
  39.         // Check for cancelation.  
  40.         final boolean canceled = resetCancelNextUpFlag(this)  
  41.                 || actionMasked == MotionEvent.ACTION_CANCEL;  
  42.   
  43.         // Update list of touch targets for pointer down, if needed.  
  44.         final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;  
  45.         TouchTarget newTouchTarget = null;  
  46.         boolean alreadyDispatchedToNewTouchTarget = false;  
  47.          //這裏面一大堆是派發事件到子View,如果intercepted是true,則直接跳過  
  48.         if (!canceled && !intercepted) {  
  49.             if (actionMasked == MotionEvent.ACTION_DOWN  
  50.                     || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)  
  51.                     || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {  
  52.                 final int actionIndex = ev.getActionIndex(); // always 0 for down  
  53.                 final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)  
  54.                         : TouchTarget.ALL_POINTER_IDS;  
  55.   
  56.                 // Clean up earlier touch targets for this pointer id in case they  
  57.                 // have become out of sync.  
  58.                 removePointersFromTouchTargets(idBitsToAssign);  
  59.   
  60.                 final int childrenCount = mChildrenCount;  
  61.                 if (newTouchTarget == null && childrenCount != 0) {  
  62.                     final float x = ev.getX(actionIndex);  
  63.                     final float y = ev.getY(actionIndex);  
  64.                     // Find a child that can receive the event.  
  65.                     // Scan children from front to back.  
  66.                     final View[] children = mChildren;  
  67.   
  68.                     final boolean customOrder = isChildrenDrawingOrderEnabled();  
  69.                     for (int i = childrenCount - 1; i >= 0; i--) {  
  70.                         final int childIndex = customOrder ?  
  71.                                 getChildDrawingOrder(childrenCount, i) : i;  
  72.                         final View child = children[childIndex];  
  73.                         if (!canViewReceivePointerEvents(child)  
  74.                                 || !isTransformedTouchPointInView(x, y, child, null)) {  
  75.                             continue;  
  76.                         }  
  77.   
  78.                         newTouchTarget = getTouchTarget(child);  
  79.                         if (newTouchTarget != null) {  
  80.                             // Child is already receiving touch within its bounds.  
  81.                             // Give it the new pointer in addition to the ones it is handling.  
  82.                             newTouchTarget.pointerIdBits |= idBitsToAssign;  
  83.                             break;  
  84.                         }  
  85.   
  86.                         resetCancelNextUpFlag(child);  
  87.                         if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {  
  88.                             // Child wants to receive touch within its bounds.  
  89.                             mLastTouchDownTime = ev.getDownTime();  
  90.                             mLastTouchDownIndex = childIndex;  
  91.                             mLastTouchDownX = ev.getX();  
  92.                             mLastTouchDownY = ev.getY();  
  93.                             //注意下面兩句,如果有子View處理了點擊事件,則newTouchTarget會被賦值,  
  94.                             //同時alreadyDispatchedToNewTouchTarget也會爲true,這兩個變量是直接影響下面的代碼邏輯的。  
  95.                             newTouchTarget = addTouchTarget(child, idBitsToAssign);  
  96.                             alreadyDispatchedToNewTouchTarget = true;  
  97.                             break;  
  98.                         }  
  99.                     }  
  100.                 }  
  101.   
  102.                 if (newTouchTarget == null && mFirstTouchTarget != null) {  
  103.                     // Did not find a child to receive the event.  
  104.                     // Assign the pointer to the least recently added target.  
  105.                     newTouchTarget = mFirstTouchTarget;  
  106.                     while (newTouchTarget.next != null) {  
  107.                         newTouchTarget = newTouchTarget.next;  
  108.                     }  
  109.                     newTouchTarget.pointerIdBits |= idBitsToAssign;  
  110.                 }  
  111.             }  
  112.         }  
  113.   
  114.         // Dispatch to touch targets.  
  115.      //這裏如果當前ViewGroup攔截了事件,或者其子View的onTouchEvent都返回了false,則事件會由ViewGroup處理  
  116.         if (mFirstTouchTarget == null) {  
  117.             // No touch targets so treat this as an ordinary view.  
  118.           //這裏就是ViewGroup對點擊事件的處理  
  119.             handled = dispatchTransformedTouchEvent(ev, canceled, null,  
  120.                     TouchTarget.ALL_POINTER_IDS);  
  121.         } else {  
  122.             // Dispatch to touch targets, excluding the new touch target if we already  
  123.             // dispatched to it.  Cancel touch targets if necessary.  
  124.             TouchTarget predecessor = null;  
  125.             TouchTarget target = mFirstTouchTarget;  
  126.             while (target != null) {  
  127.                 final TouchTarget next = target.next;  
  128.                 if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {  
  129.                     handled = true;  
  130.                 } else {  
  131.                     final boolean cancelChild = resetCancelNextUpFlag(target.child)  
  132.                             || intercepted;  
  133.                     if (dispatchTransformedTouchEvent(ev, cancelChild,  
  134.                             target.child, target.pointerIdBits)) {  
  135.                         handled = true;  
  136.                     }  
  137.                     if (cancelChild) {  
  138.                         if (predecessor == null) {  
  139.                             mFirstTouchTarget = next;  
  140.                         } else {  
  141.                             predecessor.next = next;  
  142.                         }  
  143.                         target.recycle();  
  144.                         target = next;  
  145.                         continue;  
  146.                     }  
  147.                 }  
  148.                 predecessor = target;  
  149.                 target = next;  
  150.             }  
  151.         }  
  152.   
  153.         // Update list of touch targets for pointer up or cancel, if needed.  
  154.         if (canceled  
  155.                 || actionMasked == MotionEvent.ACTION_UP  
  156.                 || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {  
  157.             resetTouchState();  
  158.         } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {  
  159.             final int actionIndex = ev.getActionIndex();  
  160.             final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);  
  161.             removePointersFromTouchTargets(idBitsToRemove);  
  162.         }  
  163.     }  
  164.   
  165.     if (!handled && mInputEventConsistencyVerifier != null) {  
  166.         mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);  
  167.     }  
  168.     return handled;  
  169. }  

下面再看ViewGroup對點擊事件的處理

Code:ViewGroup#dispatchTransformedTouchEvent

  1. /** 
  2.  * Transforms a motion event into the coordinate space of a particular child view, 
  3.  * filters out irrelevant pointer ids, and overrides its action if necessary. 
  4.  * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead. 
  5.  */  
  6. private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,  
  7.         View child, int desiredPointerIdBits) {  
  8.     final boolean handled;  
  9.   
  10.     // Canceling motions is a special case.  We don't need to perform any transformations  
  11.     // or filtering.  The important part is the action, not the contents.  
  12.     final int oldAction = event.getAction();  
  13.     if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {  
  14.         event.setAction(MotionEvent.ACTION_CANCEL);  
  15.         if (child == null) {  
  16.       //這裏就是ViewGroup對點擊事件的處理,其調用了View的dispatchTouchEvent方法  
  17.             handled = super.dispatchTouchEvent(event);  
  18.         } else {  
  19.             handled = child.dispatchTouchEvent(event);  
  20.         }  
  21.         event.setAction(oldAction);  
  22.         return handled;  
  23.     }  
  24.   
  25.     // Calculate the number of pointers to deliver.  
  26.     final int oldPointerIdBits = event.getPointerIdBits();  
  27.     final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;  
  28.   
  29.     // If for some reason we ended up in an inconsistent state where it looks like we  
  30.     // might produce a motion event with no pointers in it, then drop the event.  
  31.     if (newPointerIdBits == 0) {  
  32.         return false;  
  33.     }  
  34.   
  35.     // If the number of pointers is the same and we don't need to perform any fancy  
  36.     // irreversible transformations, then we can reuse the motion event for this  
  37.     // dispatch as long as we are careful to revert any changes we make.  
  38.     // Otherwise we need to make a copy.  
  39.     final MotionEvent transformedEvent;  
  40.     if (newPointerIdBits == oldPointerIdBits) {  
  41.         if (child == null || child.hasIdentityMatrix()) {  
  42.             if (child == null) {  
  43.                 handled = super.dispatchTouchEvent(event);  
  44.             } else {  
  45.                 final float offsetX = mScrollX - child.mLeft;  
  46.                 final float offsetY = mScrollY - child.mTop;  
  47.                 event.offsetLocation(offsetX, offsetY);  
  48.   
  49.                 handled = child.dispatchTouchEvent(event);  
  50.   
  51.                 event.offsetLocation(-offsetX, -offsetY);  
  52.             }  
  53.             return handled;  
  54.         }  
  55.         transformedEvent = MotionEvent.obtain(event);  
  56.     } else {  
  57.         transformedEvent = event.split(newPointerIdBits);  
  58.     }  
  59.   
  60.     // Perform any necessary transformations and dispatch.  
  61.     if (child == null) {  
  62.         handled = super.dispatchTouchEvent(transformedEvent);  
  63.     } else {  
  64.         final float offsetX = mScrollX - child.mLeft;  
  65.         final float offsetY = mScrollY - child.mTop;  
  66.         transformedEvent.offsetLocation(offsetX, offsetY);  
  67.         if (! child.hasIdentityMatrix()) {  
  68.             transformedEvent.transform(child.getInverseMatrix());  
  69.         }  
  70.   
  71.         handled = child.dispatchTouchEvent(transformedEvent);  
  72.     }  
  73.   
  74.     // Done.  
  75.     transformedEvent.recycle();  
  76.     return handled;  
  77. }  
再看

Code:View#dispatchTouchEvent

  1. /** 
  2.   * Pass the touch screen motion event down to the target view, or this 
  3.   * view if it is the target. 
  4.   * 
  5.   * @param event The motion event to be dispatched. 
  6.   * @return True if the event was handled by the view, false otherwise. 
  7.   */  
  8.  public boolean dispatchTouchEvent(MotionEvent event) {  
  9.      if (mInputEventConsistencyVerifier != null) {  
  10.          mInputEventConsistencyVerifier.onTouchEvent(event, 0);  
  11.      }  
  12.   
  13.      if (onFilterTouchEventForSecurity(event)) {  
  14.          //noinspection SimplifiableIfStatement  
  15.          ListenerInfo li = mListenerInfo;  
  16.          if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED  
  17.                  && li.mOnTouchListener.onTouch(this, event)) {  
  18.              return true;  
  19.          }  
  20.   
  21.          if (onTouchEvent(event)) {  
  22.              return true;  
  23.          }  
  24.      }  
  25.   
  26.      if (mInputEventConsistencyVerifier != null) {  
  27.          mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);  
  28.      }  
  29.      return false;  
  30.  }  
這段代碼比較簡單,View對事件的處理是這樣的:如果設置了OnTouchListener就調用onTouch,否則就直接調用onTouchEvent,而onClick是在onTouchEvent內部通過performClick觸發的。簡單來說,事件如果被ViewGroup攔截或者子View的onTouchEvent都返回了false,則事件最終由ViewGroup處理。

3.無人處理的點擊事件

如果一個點擊事件,子View的onTouchEvent返回了false,則父View的onTouchEvent會被直接調用,以此類推。如果所有的View都不處理,則最終會由Activity來處理,這個時候,Activity的onTouchEvent會被調用。這個問題已經在1和2中做了說明。

發佈了51 篇原創文章 · 獲贊 8 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章