android 事件分發

憤怒的小鹹菜發表於2018-08-28

ViewGroup與View

  ViewGroup和View事件的分發,攔截,消費的相關方法如下表:

型別 相關方法 ViewGroup View
事件分發 dispatchTouchEvent
事件攔截 onInterceptTouchEvent
事件消費 onTouchEvent

這個三個方法的返回值均是Boolean型別,通過true和false來控制事件的傳遞和消費流程。我們先通過實際例子來看看事件傳遞,消費的流程。
xml:

<?xml version="1.0" encoding="utf-8"?>
<com.aoy.touch.TouchViewGroup xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.aoy.touch.MainActivity">

     <com.aoy.touch.TouchChildView
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:background="@color/colorPrimary"
        android:text="TouchChild"
        android:gravity="center"
        android:textSize="16sp"
        android:textColor="#ffffff"
        android:layout_centerInParent="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</com.aoy.touch.TouchViewGroup>
複製程式碼

TouchViewGroup:

class TouchViewGroup : RelativeLayout {
    val TAG : String = "TouchStudy"

    constructor(ctx: Context):super(ctx)

    constructor(ctx: Context,attrs: AttributeSet):super(ctx,attrs)

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        when(ev!!.action){
            MotionEvent.ACTION_DOWN -> {
                Log.i(TAG,"ParentView dispatchTouchEvent ACTION_DOWN")
            }
            MotionEvent.ACTION_MOVE -> {
                Log.i(TAG,"ParentView dispatchTouchEvent ACTION_MOVE")
            }
            MotionEvent.ACTION_UP,MotionEvent.ACTION_CANCEL ->{
                Log.i(TAG,"ParentView dispatchTouchEvent ACTION_CANCEL")
            }
        }
        var ret = super.dispatchTouchEvent(ev)
        Log.i(TAG,"ParentView dispatchTouchEvent return :" + ret)

        return ret
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        when(ev!!.action){
            MotionEvent.ACTION_DOWN -> {
                Log.i(TAG,"ParentView onInterceptTouchEvent ACTION_DOWN")
            }
            MotionEvent.ACTION_MOVE -> {
                Log.i(TAG,"ParentView onInterceptTouchEvent ACTION_MOVE")
             //   return true
            }
            MotionEvent.ACTION_UP,MotionEvent.ACTION_CANCEL ->{
                Log.i(TAG,"ParentView onInterceptTouchEvent ACTION_CANCEL")
            }
        }
        var ret = super.onInterceptTouchEvent(ev)
        Log.i(TAG,"ParentView onInterceptTouchEvent return :" + ret)
        return ret
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event!!.action) {
            MotionEvent.ACTION_DOWN -> {
                Log.i(TAG, "ParentView onTouchEvent ACTION_DOWN")
            }
            MotionEvent.ACTION_MOVE -> {
                Log.i(TAG, "ParentView onTouchEvent ACTION_MOVE")
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                Log.i(TAG, "ParentView onTouchEvent ACTION_CANCEL")
            }
        }
        var ret = super.onTouchEvent(event)
        Log.i(TAG,"ParentView onTouchEvent return :" + ret)
        return super.onTouchEvent(event)
    }
}
複製程式碼

TouchChildView:

class TouchChildView : TextView {
    val TAG : String = "TouchStudy"

    constructor(ctx: Context): super(ctx)
    constructor(ctx: Context,attrs: AttributeSet): super(ctx,attrs)

    override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
        when(event!!.action){
            MotionEvent.ACTION_DOWN -> {
                Log.i(TAG,"ChildView dispatchTouchEvent ACTION_DOWN")
            }
            MotionEvent.ACTION_MOVE -> {
                Log.i(TAG,"ChildView dispatchTouchEvent ACTION_MOVE")
            }
            MotionEvent.ACTION_UP,MotionEvent.ACTION_CANCEL ->{
                Log.i(TAG,"ChildView dispatchTouchEvent ACTION_CANCEL")
            }
        }
        var ret : Boolean = super.dispatchTouchEvent(event)
        Log.i(TAG,"ChildView dispatchTouchEvent return :" + ret)
        return ret
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event!!.action) {
            MotionEvent.ACTION_DOWN -> {
                Log.i(TAG, "ChildView onTouchEvent ACTION_DOWN")
            }
            MotionEvent.ACTION_MOVE -> {
                Log.i(TAG, "ChildView onTouchEvent ACTION_MOVE")
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                Log.i(TAG, "ChildView onTouchEvent ACTION_CANCEL")
            }
        }
        var ret : Boolean = super.onTouchEvent(event)
        Log.i(TAG,"ChildView onTouchEvent return :" + ret)
        return ret
    }
}
複製程式碼

TouchViewGroup與TouchChildView主要是將接收到的事件列印出來。

效果圖
   初始狀態下childView的onTouchEvent()和parentView的OnTouchEvent()都不消耗ACTION_DOWN事件,同時parentView也不攔截ACTION_DOWN事件,在TouchChild範圍內滑動一下,我們看下log列印:

TouchStudy: ParentView dispatchTouchEvent ACTION_DOWN
TouchStudy: ParentView onInterceptTouchEvent ACTION_DOWN
TouchStudy: ParentView onInterceptTouchEvent return :false
TouchStudy: ChildView dispatchTouchEvent ACTION_DOWN
TouchStudy: ChildView onTouchEvent ACTION_DOWN
TouchStudy: ChildView onTouchEvent return :false
TouchStudy: ChildView dispatchTouchEvent return :false
TouchStudy: ParentView onTouchEvent ACTION_DOWN
TouchStudy: ParentView onTouchEvent return :false
TouchStudy: ParentView dispatchTouchEvent return :false
複製程式碼

其事件的分發消費流程如下圖 :

android 事件分發

  由於childView在onTouchEvent()中沒有消耗down事件導致childView dispatchTouchEvent返回false,這會讓ParentView不會把後續的ACTION_MOVE和ACTION_UP分發給childView。同理由於childView和parentView的onTouchEvent()都沒有消耗down事件,所以parentView也沒有收到後續的ACTION_DOWN和ACTION_UP事件。

   現在我們讓childView的onTouchEvent()消耗ACTION_DOWN事件,但ViewGroup中不攔截ACTION_DOWN事件,改動程式碼如下:

  /**
   * childView onTouchEvent
   */
  override fun onTouchEvent(event: MotionEvent?): Boolean {
      when (event!!.action) {
          MotionEvent.ACTION_DOWN -> {
              Log.i(TAG, "ChildView onTouchEvent ACTION_DOWN")
              return true
          }
          MotionEvent.ACTION_MOVE -> {
              Log.i(TAG, "ChildView onTouchEvent ACTION_MOVE")
          }
          MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
              Log.i(TAG, "ChildView onTouchEvent ACTION_CANCEL")
          }
      }
      var ret : Boolean = super.onTouchEvent(event)
      Log.i(TAG,"ChildView onTouchEvent return :" + ret)
      return ret
  }
複製程式碼

  在childView中滑動之後,其log為:

TouchStudy: ParentView dispatchTouchEvent ACTION_DOWN
TouchStudy: ParentView onInterceptTouchEvent ACTION_DOWN
TouchStudy: ParentView onInterceptTouchEvent return :false
TouchStudy: ChildView dispatchTouchEvent ACTION_DOWN
TouchStudy: ChildView onTouchEvent ACTION_DOWN
TouchStudy: ChildView onTouchEvent return :true
TouchStudy: ChildView dispatchTouchEvent return :true
TouchStudy: ParentView dispatchTouchEvent return :true
TouchStudy: ParentView dispatchTouchEvent ACTION_MOVE
TouchStudy: ParentView onInterceptTouchEvent ACTION_MOVE
TouchStudy: ParentView onInterceptTouchEvent return :false
TouchStudy: ChildView dispatchTouchEvent ACTION_MOVE
TouchStudy: ChildView onTouchEvent ACTION_MOVE
TouchStudy: ChildView onTouchEvent return :false
TouchStudy: ChildView dispatchTouchEvent return :false
TouchStudy: ParentView dispatchTouchEvent return :false
TouchStudy: ParentView dispatchTouchEvent ACTION_MOVE
TouchStudy: ParentView onInterceptTouchEvent ACTION_MOVE
TouchStudy: ParentView onInterceptTouchEvent return :false
TouchStudy: ChildView dispatchTouchEvent ACTION_MOVE
TouchStudy: ChildView onTouchEvent ACTION_MOVE
TouchStudy: ChildView onTouchEvent return :false
TouchStudy: ChildView dispatchTouchEvent return :false
TouchStudy: ParentView dispatchTouchEvent return :false
TouchStudy: ParentView dispatchTouchEvent ACTION_CANCEL
TouchStudy: ParentView onInterceptTouchEvent ACTION_CANCEL
TouchStudy: ParentView onInterceptTouchEvent return :false
TouchStudy: ChildView dispatchTouchEvent ACTION_CANCEL
TouchStudy: ChildView onTouchEvent ACTION_CANCEL
TouchStudy: ChildView onTouchEvent return :false
TouchStudy: ChildView dispatchTouchEvent return :false
TouchStudy: ParentView dispatchTouchEvent return :false
複製程式碼

  其ACTION_DOWN事件的分發,消費流程圖如下:

android 事件分發

  其ACTION_MOVE和ACITON_UP(ACTION_CANCEL)事件的分發,消費入下圖:
android 事件分發
  通過log可以看到,ACTION_MOVE與ACTION_DOWN有很大不同,當childView不消費ACTION_DOWN事件時,childView將不會收到後續的ACTION_MOVE與ACTION_UP事件,但是如果childView消費了ACTION_DOWN事件,在parentView不攔截事件的情況下,不管childView是否消費ACTION_MOVE事件,childView 還是會收到後續的ACTION_MOVE和ACTION_UP事件。換句話說View是否消費完整的一系列事件(完整的一系列事件指的是:手指按下到抬起中間所產生的所有事件)的關鍵取決與是否消費了ACTION_DOWN事件

   讓ViewGroup中攔截ACTION_DOWN事件,改動程式碼如下:

 /**
   * parentView  onInterceptTouchEvent
   */
  override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
      when(ev!!.action){
          MotionEvent.ACTION_DOWN -> {
              Log.i(TAG,"ParentView onInterceptTouchEvent ACTION_DOWN")
              return true;
          }
          MotionEvent.ACTION_MOVE -> {
              Log.i(TAG,"ParentView onInterceptTouchEvent ACTION_MOVE")
           //   return true
          }
          MotionEvent.ACTION_UP,MotionEvent.ACTION_CANCEL ->{
              Log.i(TAG,"ParentView onInterceptTouchEvent ACTION_CANCEL")
          }
      }
      var ret = super.onInterceptTouchEvent(ev)
      Log.i(TAG,"ParentView onInterceptTouchEvent return :" + ret)
      return ret
  }
  
  /**
   * childView onTouchEvent
   */
  override fun onTouchEvent(event: MotionEvent?): Boolean {
      when (event!!.action) {
          MotionEvent.ACTION_DOWN -> {
              Log.i(TAG, "ChildView onTouchEvent ACTION_DOWN")
              Log.i(TAG,"ChildView onTouchEvent return :" + true)
              return true
          }
          MotionEvent.ACTION_MOVE -> {
              Log.i(TAG, "ChildView onTouchEvent ACTION_MOVE")
          }
          MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
              Log.i(TAG, "ChildView onTouchEvent ACTION_CANCEL")
          }
      }
      var ret : Boolean = super.onTouchEvent(event)
      Log.i(TAG,"ChildView onTouchEvent return :" + ret)
      return ret
  }
複製程式碼

  這種情景下的執行log如下:

TouchStudy: ParentView dispatchTouchEvent ACTION_DOWN
TouchStudy: ParentView onInterceptTouchEvent ACTION_DOWN
TouchStudy: ParentView onTouchEvent ACTION_DOWN
TouchStudy: ParentView onTouchEvent return :false
TouchStudy: ParentView dispatchTouchEvent return :false
複製程式碼

ACTION_DOWN事件的分發消費流程圖:

android 事件分發

這種情況下,parentView不會將任何事件分發給childView,同時parentView也沒有消費ACTION_DOWN事件,導致parentView不會收到ACTION_MOVE,ACTION_UP等事件。

   讓childView消耗ACTION_DOWN事件,同時讓ViewGroup中攔截ACTION_MOVE事件,改動程式碼如下:

 /**
   * parentView  onInterceptTouchEvent
   */
  override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
      when(ev!!.action){
          MotionEvent.ACTION_DOWN -> {
              Log.i(TAG,"ParentView onInterceptTouchEvent ACTION_DOWN")
          }
          MotionEvent.ACTION_MOVE -> {
              Log.i(TAG,"ParentView onInterceptTouchEvent ACTION_MOVE")
              return true
          }
          MotionEvent.ACTION_UP,MotionEvent.ACTION_CANCEL ->{
              Log.i(TAG,"ParentView onInterceptTouchEvent ACTION_CANCEL")
          }
      }
      var ret = super.onInterceptTouchEvent(ev)
      Log.i(TAG,"ParentView onInterceptTouchEvent return :" + ret)
      return ret
  }
  
  /**
   * childView onTouchEvent
   */
  override fun onTouchEvent(event: MotionEvent?): Boolean {
      when (event!!.action) {
          MotionEvent.ACTION_DOWN -> {
              Log.i(TAG, "ChildView onTouchEvent ACTION_DOWN")
              Log.i(TAG,"ChildView onTouchEvent return :" + true)
              return true
          }
          MotionEvent.ACTION_MOVE -> {
              Log.i(TAG, "ChildView onTouchEvent ACTION_MOVE")
          }
          MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
              Log.i(TAG, "ChildView onTouchEvent ACTION_CANCEL")
          }
      }
      var ret : Boolean = super.onTouchEvent(event)
      Log.i(TAG,"ChildView onTouchEvent return :" + ret)
      return ret
  }
複製程式碼

其執行log如下:

TouchStudy: ParentView dispatchTouchEvent ACTION_DOWN
TouchStudy: ParentView onInterceptTouchEvent ACTION_DOWN
TouchStudy: ParentView onInterceptTouchEvent return :false
TouchStudy: ChildView dispatchTouchEvent ACTION_DOWN
TouchStudy: ChildView onTouchEvent ACTION_DOWN
TouchStudy: ChildView onTouchEvent return :true
TouchStudy: ChildView dispatchTouchEvent return :true
TouchStudy: ParentView dispatchTouchEvent return :true
TouchStudy: ParentView dispatchTouchEvent ACTION_MOVE
TouchStudy: ParentView onInterceptTouchEvent ACTION_MOVE
TouchStudy: ChildView dispatchTouchEvent ACTION_CANCEL
TouchStudy: ChildView onTouchEvent ACTION_CANCEL
TouchStudy: ChildView onTouchEvent return :false
TouchStudy: ChildView dispatchTouchEvent return :false
TouchStudy: ParentView dispatchTouchEvent return :false
TouchStudy: ParentView dispatchTouchEvent ACTION_MOVE
TouchStudy: ParentView onTouchEvent ACTION_MOVE
TouchStudy: ParentView dispatchTouchEvent ACTION_CANCEL
TouchStudy: ParentView onTouchEvent ACTION_CANCEL
TouchStudy: ParentView onTouchEvent return :false
TouchStudy: ParentView dispatchTouchEvent return :false
複製程式碼

ACTION_DOWN事件的分發消費過程圖:

android 事件分發

ACTION_MOVE的分發消費過程圖:

android 事件分發

  從③和④兩種情況可以看出當parentView攔截ACTION_DOWN事件後,childView將不會收到ACTION_DOWN事和後續的ACTION_MOVE與ACTION_UP事件,而parentView能否收到後續的事件,取決於parentView的onTouchEvent是否消費ACTION_DOWN事件。當childView消費了ACTION_DOWN事件後,如果parentView攔截ACTION_MOVE事件,則後續的一系列事件都將交由parentView的ontouchEvent()來處理,不會再走onInterceptionEvent()方法,childView將不會收到後續的任何事件。

  結論:
  (1)不管是GroupView還是View,消費事件指的是消費ACTION_DOWN事件,只有消費了ACTION_DOWN事件,才有可能接收分發後續的ACTION_MOVE和ACTION_UP等事件。

  (2)對於View而言,消耗ACTION_DOWN事件只有一種途徑:在onTouchEvent()中接受到ACTION_DOWN時返回true。  而GroupVie消耗ACTION_DOWN事件有兩種途徑:①其child view消費ACTION_DOWN;②其自身消耗ACTION_DOWN事件,即在其自身的onTouchEvent()中接受到ACTION_DOWN事件時返回true,這兩種消耗ACTION_DOWN事件的關係為:parentView會先view是否消耗ACTION_DOWN分發給child view,讓child view決定是否消耗ACTION_DOWN,只有當child view不消耗時,才將ACTION_DONW事件傳遞給其本身的onTouchEvent()方法讓其判斷是否消費ACTION_DOWN方法。

  (3)當GroupView攔截某一事件時,GroupView 不會將這一事件和後續的所有事件分發給child view,攔截的這一事件將會交給GroupView的onTouchEvent()處理。對於後續GroupView接收到的所有事件不會走攔截過程,而是直接交由GroupView的onTouchEvent()處理。

原始碼分析

  以下所有的原始碼都是基於API26(android 8.0)

View 的dispatchTouchEvent原始碼:

 public boolean dispatchTouchEvent(MotionEvent event) {
       ...

        if (onFilterTouchEventForSecurity(event)) {
        
        //關注點一:當View為可點選並且在拖動scrollBar時直接消費事件
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            
        //關注點二:當View設定為可點選並且並且設定OnTouchListener處理時,直接消費事件,並將所有的一系列事件交由OnTouchListener處理
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
        //關注點三:如果不是拖動scrollBar並且沒有設定OnTouchListener則事件交由onTouchEvent()處理
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }

        if (!result && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }

      
        if (actionMasked == MotionEvent.ACTION_UP ||
                actionMasked == MotionEvent.ACTION_CANCEL ||
                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
            stopNestedScroll();
        }

        return result;
    }
複製程式碼

  從“關注點二”和“關注點三”中可以看出如果View設定了OnTouchListener則view直接消費事件,並將所有的事件都交由OnTouchListener處理,就onTouchEvent()什麼事了,如果沒有設定OnTouchListener,則是否消費事件由onTouchEvent()決定,下面看看View的onTouchEvent()原始碼。onTouchEvent原始碼較長,挑重點來看

public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();

        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;

       ...

        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
                case MotionEvent.ACTION_UP:
                    ...
                    break;

                case MotionEvent.ACTION_DOWN:
                   ...
                    break;

                case MotionEvent.ACTION_CANCEL:
                   ...

                case MotionEvent.ACTION_MOVE:
                   ...
                    break;
            }

            return true;
        }

        return false;
    }
複製程式碼

  View的onTouchEvent()比較好理解,如果View設定為可點選或設定OnLongClickListener,OnClickListenerView就消費了事件。switch裡的程式碼是具體處理長按監聽和點選事件等事情。

  GroupView的dispatchTouchEvent()就比較複雜了,下面通過關鍵原始碼來看看GroupView是如何分發消費事件的。

 public boolean dispatchTouchEvent(MotionEvent ev) {
       ...
        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            if (actionMasked == MotionEvent.ACTION_DOWN) {
               //關注點一:接收到ACTION_DOWN事件時,將mFirstTouchTarget設定為 null
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }

            final boolean intercepted;
            //關注點二:當處理ACTION_DOWN或mFirstTouchTarget不為空是走攔截流程
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget不為空是走攔截流程 != null) {
                /*關注點三:是否不允許攔截事件,當child View呼叫
                parent.requestDisallowInterceptTouchEvent()時,disallowIntercept = true*/
                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 {
            
                intercepted = true;
            }

            if (intercepted || mFirstTouchTarget != null) {
                ev.setTargetAccessibilityFocus(false);
            }

            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
          
            if (!canceled && !intercepted) {
                ...
                /*關注點四:只有當事件為ACTION_DOWN或者為多點觸控的ACTION_POINTER_DOWN或者滑鼠懸浮事件時,
                才會去在child view中尋找消費事件的view*/
                if (actionMasked == MotionEvent.ACTION_DOWN
                        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                    final int actionIndex = ev.getActionIndex(); 
                    //識別手指的標誌位
                    final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
                            : TouchTarget.ALL_POINTER_IDS;

                
                    removePointersFromTouchTargets(idBitsToAssign);

                    final int childrenCount = mChildrenCount;
                    if (newTouchTarget == null && childrenCount != 0) {
                        final float x = ev.getX(actionIndex);
                        final float y = ev.getY(actionIndex);
             /*關注點五:先根據Z軸方法z座標值大小排序,(Z軸是三維座標系裡的Z方向,cardView設定陰影是就是設定Z軸的值),
             再根據child view的繪製順序排序*/
                        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);

                            ...
                            //關注點六:如果child view 不可見,並且事件不是發生在child view的範圍內直接跳出查詢下一個child view
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }

                            newTouchTarget = getTouchTarget(child);
                            if (newTouchTarget != null) {
                                newTouchTarget.pointerIdBits |= idBitsToAssign;
                                break;
                            }

                            resetCancelNextUpFlag(child);
                            //關注點七:如果找到處理這一事件的child view,給mFirstTouchTarget賦值。
                            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();
                                //關注點八:給mFirstTouchTarget賦值
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }

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

            // 關注點九:如果沒有找到child view去消費事件,將事件分發給自己,判斷是否消費事件
            if (mFirstTouchTarget == null) {
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
              
                TouchTarget predecessor = null;
                TouchTarget target = mFirstTouchTarget;
                //遍歷mFirstTouchTarget這個連結串列
                while (target != null) {
                    final TouchTarget next = target.next;
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                    /* 關注點十:如果child view消耗事件,判斷是否攔截事件,如果攔截事件則child view 將不會收到這次事件,而是收到
                    ACTION_CANCEL事件,而mFirstTouchTarget最終將會賦值為null;如果不攔截事件,則按正常流程將事件分發給child view */
                        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;
                }
            }

            /*關注點十一:當接受到的事件時ACTION_UP,ACTION_CANCEL事件時,將
            mFirstTouchTarget設定為null,重置FLAG_DISALLOW_INTERCEPT位*/
            if (canceled
                    || actionMasked == MotionEvent.ACTION_UP
                    || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                resetTouchState();
            } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
                final int actionIndex = ev.getActionIndex();
                final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
                removePointersFromTouchTargets(idBitsToRemove);
            }
        }

        if (!handled && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
        }
        return handled;
    }
複製程式碼
  •   重點關注下mFirstTouchTarget這個物件,mFirstTouchTarget是一個連結串列結構的物件,正常情況下這個連結串列只有一個元素,當GroupView允許處理多點觸控事件時,並且多點觸控發生時mFirstTouchTarget可能會有多個元素。多點觸控事件的分發消費流程與單點觸控的流程相似,下面的說明都是以單點觸控為例說明。
  •   ‘關注點五’註釋的程式碼說明了ACTION_DOWN事件是按照child view繪製順序來分發事件的,先繪製的child view會優先收到ACTION_DOWN事件。
  •   ‘關注點四’到‘關注點九’之間的程式碼就是ACTION_DOWN事件的分發消費過程。如果child view消費了ACTION_DOWN事件,在‘關注點八’的程式碼就給mFirstTouchTarget賦值,否則mFirstTouchTarget為null。
  •   ‘關注點九’說明如果child view沒有消費ACTION_DOWN事件,其是絕對不會接受到後續的ACTION_MOVE,ACTION_UP等事件,換句話說view消費事件指的是是否消費ACTION_DOWN事件。至於消費了ACTION_DOWN事件之後,能否接受到後續的事件,就要看paren view是否攔截事件了。
  •   ‘關注點十’程式碼是mFirstTouchTarget的遍歷過程,如果parentView攔截了事件,則child view會收到ACITON_CANCEL事件,同時mFirstTouchTarget會通過連結串列的遍歷會最終賦值為null,這回導致後續的事件不會分發給child view而是執行‘關注點九’的程式碼。

下面是dispatchTransformedTouchEvent()的程式碼分析。

//當事件由GroupView自己處理則child = null
 private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        final boolean handled;

        final int oldAction = event.getAction();
        //當GroupView攔截事件時cancel = true
        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
            event.setAction(MotionEvent.ACTION_CANCEL);
            if (child == null) {
            //GroupView自己處理事件。 GroupView繼承製View,super.dispatchTouchEvent就是呼叫View.dispatchTouchEvent
                handled = super.dispatchTouchEvent(event);
            } else {
            //將事件分發給child view處理
                handled = child.dispatchTouchEvent(event);
            }
            event.setAction(oldAction);
            return handled;
        }

        // 獲取此次事件的所有手指標識位|運算值{@link MotionEvent#getPointerIdBits()}
        final int oldPointerIdBits = event.getPointerIdBits();
        final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;

       //如果此次事件不合法,不處理
        if (newPointerIdBits == 0) {
            return false;
        }

    
        final MotionEvent transformedEvent;
        //單點觸控處理
        if (newPointerIdBits == oldPointerIdBits) {
            if (child == null || child.hasIdentityMatrix()) {
                if (child == null) {
                    handled = super.dispatchTouchEvent(event);
                } else {
                    final float offsetX = mScrollX - child.mLeft;
                    final float offsetY = mScrollY - child.mTop;
                    event.offsetLocation(offsetX, offsetY);

                    handled = child.dispatchTouchEvent(event);

                    event.offsetLocation(-offsetX, -offsetY);
                }
                return handled;
            }
            transformedEvent = MotionEvent.obtain(event);
        } else {
        //多點觸控處理
            transformedEvent = event.split(newPointerIdBits);
        }

        if (child == null) {
            handled = super.dispatchTouchEvent(transformedEvent);
        } else {
            final float offsetX = mScrollX - child.mLeft;
            final float offsetY = mScrollY - child.mTop;
            transformedEvent.offsetLocation(offsetX, offsetY);
            if (! child.hasIdentityMatrix()) {
                transformedEvent.transform(child.getInverseMatrix());
            }

            handled = child.dispatchTouchEvent(transformedEvent);
        }

        transformedEvent.recycle();
        return handled;
    }
複製程式碼

  事件從activity到child view的完整分發消費圖:

android 事件分發

相關文章