Android 深入探究自定義view之事件的分發機制與處理詳解

本文主要探討下面幾個問題:

  • 學習事件分發機制是為瞭解決什麼問題
  • Activity對事件的分發過程
  • 父佈局攔截的分發處理過程
  • 父佈局不攔截時的分發處理過程
  • 沖突解決方案

題引

事件隻有一個,多個人想要處理,處理的對象不是我們想給的對象就是事件沖突。

在這裡插入圖片描述

如上圖,RecyclerView 的父佈局是ViewPager,左右滑動時沒問題,上下滑動時RecyclerView好像沒收到滑動事件一樣,無法達到我們預期的效果。我們的觸摸被封裝成MotionEvent事件傳遞,在多個層級中它是如何傳遞的呢?又是根據什麼來確定哪個view處理這個事件的呢,咱們抽絲剝繭一步步揭開她的面紗!

Activity對事件的分發過程

追溯本源,尋找事件分發的開始。

當一個點擊操作發生時,事件最先傳遞給當前的Activity,由Activity的dispatchTouchEvent進行分發

    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

這裡的getWindow返回的window類隻有一個實現,PhoneWindow

	private DecorView mDecor

    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);
    }

我們繼續看 DecorView的superDispatchTouchEvent方法實現

    public boolean superDispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }

DecorView 繼承於 ViewGroup。此時應該理解瞭,Activity 的 事件分發交給瞭 DecorView 處理,而 DecorView 又是什麼

在這裡插入圖片描述

DecorView是activity窗口的根視圖,是一個FrameLayout,DecorView內部又分為兩部分,一部分是ActionBar,另一部分是ContentParent,即activity在setContentView對應的佈局。如此一來,事件分發從系統層面開始向我們寫的佈局分發事件!

事件分發是一個遞歸的過程,主要涉及三個函數

  • dispatchTouchEvent
  • onInterceptTouchEvent
  • onTouchEvent

三者關系

public boolean dispatchTouchEvent(MotionEvent ev){
	boolean result = false;
	if(onInterceptTouchEvent(ev)){	//	如果攔截則交給自己的 onTouchEvent 處理事件
		result = onTouchEvent(ev);
	}else{
		//	如果不攔截,交給子佈局分發,這是個層層遞歸過程
		result = chlid.dispatchTouchEvent(ev);
	}
	return result;
}

直接擼源碼是一件很痛苦的事情,多種可能的發生讓源碼可讀性很差。下面我們會從某一種特定邏輯下分析,這樣會清晰很多。每次隻分析一種情境!

父佈局攔截的分發處理過程

父佈局攔截我們分兩步,ACTION_DOWN、ACTION_MOVE

ACTION_DOWN 事件

進入 ViewGroup 的 dispatchTouchEvent 方法內

   if (actionMasked == MotionEvent.ACTION_DOWN) {
       // Throw away all previous state when starting a new touch gesture.
       // The framework may have dropped the up or cancel event for the previous gesture
       // due to an app switch, ANR, or some other state change.
       cancelAndClearTouchTargets(ev);
       resetTouchState();
   }

因為是 ACTION_DOWN 事件,先清空狀態,一個是TouchTarget的狀態,一個是 mGroupFlags。這個用不到繼續走

// Check for interception.
final boolean intercepted;
//	因為是第一次過來	 mFirstTouchTarget = null ,且是 ACTION_DOWN 事件,走入 if 內
if (actionMasked == MotionEvent.ACTION_DOWN
         || mFirstTouchTarget != null) {
     //	咱們走的是父佈局攔截事件,子佈局用尚方寶劍,disallowIntercept =false
     final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
     if (!disallowIntercept) {
     	//	咱們在這攔截, intercepted = true
         intercepted = onInterceptTouchEvent(ev);
         ev.setAction(action); // restore action in case it was changed
     } else {
         intercepted = false;
     }
 } else {
     // There are no touch targets and this action is not an initial down
     // so this view group continues to intercept touches.
     intercepted = true;
 }

代碼註釋的比較全,這邊主要是判斷本view是否攔截,如果攔截 intercepted = true 。所以後面的遍歷子view分發都進不去

//	intercepted = true , 進不去
if (!canceled && !intercepted) {
	//	這是一個遍歷子 view 接盤的故事
	for (int i = childrenCount - 1; i >= 0; i--) {
	}
}

一直往下走

// 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);
}

符合這個條件,深入 dispatchTransformedTouchEvent 函數,第三個參數是 null

private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
         View child, int desiredPointerIdBits) {
     
     final boolean handled;
     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);
      }
}        

第三個參數傳的是 null ,即 child = null 。調用 super 的 dispatchTouchEvent 。ViewGroup 的 super 即是 View。

handled = View.dispatchTouchEvent(event);

深入 View 的 dispatchTouchEvent 方法,主要處理邏輯是下面兩段代碼

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

我們可以得出結論:onTouch 比 onTouchEvent 優先級高,如果onTouch 攔截事件則 onTouchEvent 無法接到事件。這也是為什麼我們在onTouch方法返回true後onClick事件失效的原因。onTouchEvent 的邏輯比較簡單,此處不做分析

這裡要說明一點,事件分發機制的分發其實有兩種含義。一是事件在不同view之間的分發,父佈局到子佈局的分發;二是事件在view中對不同監聽的分發,onTouch、onClick、onLongClick 在分發時也是有順序的。

到這裡父佈局攔截的DOWN事件算結束瞭,下面是MOVE事件,繼DOWN後的滑動,這是個連續的過程

ACTION_MOVE 事件

手指點擊後開始滑動,繼續分發move事件

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); // restore action in case it was changed
    } else {
        intercepted = false;
    }
} else {
    // There are no touch targets and this action is not an initial down
    // so this view group continues to intercept touches.
    intercepted = true;
}

actionMasked = ACTION_MOVE mFirstTouchTarget = null ,直接走 else 模塊,即 intercepted = true

//	intercepted = true , 進不去
if (!canceled && !intercepted) {
	for (int i = childrenCount - 1; i >= 0; i--) {
	}
}

同樣的分發子view的模塊我們依舊進不去

// 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);
}

到這裡就跟之前的邏輯完全一樣瞭,至此父佈局的攔截過程結束
總結:

  • ViewGroup 的 onTouchEvent 方法直接調用父類(View)的實現
  • 父佈局一旦攔截Down事件,後續的move事件都直接由父佈局執行

這麼分析的好處是咱們的狀態是確定的,分析代碼不會有太多可能性搞亂邏輯,下面是父佈局不攔截的情況下事件分發

父佈局不攔截時的分發處理過程

父佈局不攔截,咱們按照正常流程走一遍,還是按上面那個思路,先 down 後 move

ACTION_DOWN

進入 GroupView 的 dispatchTouchEvent 方法後依舊西先是清空狀態,然後判斷當前佈局是否攔截

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); // restore action in case it was changed
    } else {
        intercepted = false;
    }
} else {
    // There are no touch targets and this action is not an initial down
    // so this view group continues to intercept touches.
    intercepted = true;
}

咱們的設定是不攔截,所以 intercepted = false。下面是遍歷子view的代碼

final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
    final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder);
    //	逆序拿到一個 child ,即從最上層的子view開始往內層遍歷
    final View child = getAndVerifyPreorderedView(preorderedList, children, childIndex);
    
    //	判斷觸點的位置是否在view的范圍之內或者view是否在播放動畫,如果都不滿足則直接遍歷下一個
    if (!child.canReceivePointerEvents()|| !isTransformedTouchPointInView(x, y, child, null)) {
        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);
    //	dispatchTransformedTouchEvent 函數是處理分發的函數,父佈局處理用的也是這個
    //	如果子view消費瞭事件則給標志位賦值,並 break 結束循環,如果沒有消費則繼續循環尋找分發
    if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {					註釋1
        // 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();
        //	如果子view消費瞭事件則給 alreadyDispatchedToNewTouchTarget  和 mFirstTouchTarget 賦值
        //	保存 child
        newTouchTarget = addTouchTarget(child, idBitsToAssign);							註釋2
        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);
}

分析上面幹瞭啥

  1. 從最上層的子view開始往內層遍歷
  2. 判斷當前的view在位置上是否滿足觸點位置
  3. 調用 dispatchTransformedTouchEvent 判斷是否子view消費瞭事件

如果消費瞭事件則記錄 mFirstTouchTarget 和標志位,並跳出循環

如果沒有沒有消費事件則繼續循環

註釋1的邏輯 dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)

private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
         View child, int desiredPointerIdBits) {
     
     final boolean handled;
     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);
      }
}  

這次過來 child != null ,調用的是 child.dispatchTouchEvent(event) 。child 可能是View,也可能是 ViewGroup。如果是 ViewGroup 又是一個遞歸的過程 。層層的遞歸返回 handled 告訴父佈局是否消費瞭事件!

再看註釋2的邏輯

 private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
     final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
     //	此時 mFirstTouchTarget = null
     target.next = mFirstTouchTarget;
     mFirstTouchTarget = target;
     return target;
 }

給 mFirstTouchTarget 賦值,下次 move 事件過來時 mFirstTouchTarget 就是有值的瞭!!即

  • target.next = null
  • mFirstTouchTarget = newTouchTarget
  • 保存 child 在 target 中

至此 ACTION_DOWN 事件結束

ACTION_MOVE

繼上面點擊後開始滑動

if (actionMasked == MotionEvent.ACTION_DOWN) {
      cancelAndClearTouchTargets(ev);
      resetTouchState();
  }

move事件不會重置,繼續走

 if (actionMasked == MotionEvent.ACTION_DOWN|| mFirstTouchTarget != null)

記得down事件中給mFirstTouchTarget 賦過值嘛,雖然不是down事件依舊可以進入此方法。也就是說這裡依舊會判斷父佈局是否要攔截子view,這裡也是以後咱們處理事件沖突的重點。當前的邏輯是不攔截,所以 intercepted = false

if (actionMasked == MotionEvent.ACTION_DOWN
       || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
        || actionMasked == MotionEvent.ACTION_HOVER_MOVE)

隻有ACTION_DOWN事件才會進行分發,所以不會進入遍歷子view的邏輯代碼!MOVE事件不會分發事件!

//	mFirstTouchTarget  有值,走else模塊
if (mFirstTouchTarget == null) {
    // No touch targets so treat this as an ordinary view.
    handled = dispatchTransformedTouchEvent(ev, canceled, null,TouchTarget.ALL_POINTER_IDS);
} else {
    // Dispatch to touch targets, excluding the new touch target if we already
    // dispatched to it.  Cancel touch targets if necessary.
    TouchTarget predecessor = null;
    TouchTarget target = mFirstTouchTarget;
    while (target != null) {
        final TouchTarget next = target.next;
        //	alreadyDispatchedToNewTouchTarget  是 false
        if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
            handled = true;
        } else {
        	//	此處的結果是 false
            final boolean cancelChild = resetCancelNextUpFlag(target.child)|| intercepted;
            //	在這裡被分發處理 child就是我們要分發的對象
            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;
    }
}

alreadyDispatchedToNewTouchTarget 在每次進來時都會重置為 false ,最後又會調用 dispatchTransformedTouchEvent 處理分發

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

至此move事件也結束,做個總結

  • DOWN 事件是事件分發,尋找接盤的 child 並保存在 mFirstTouchTarget 中
  • MOVE 事件雖然不需要遍歷尋找接盤的view,但還可以被ViewGroup攔截的(比如ViewPager包裹著RecyclerView,DOWN事件時被RecyclerView攔截,橫向滑動時被拋棄,這時候ViewPager是可以攔截橫向滑動接盤的)

解決沖突方案

滑動沖突解決方案有兩種:內部攔截、外部攔截。顧名思義,內部攔截是在子View中寫邏輯攔截,外部攔截則是從父佈局下手解決問題

都以ViewPager包裹RecyclerView滑動沖突為例

外部攔截

public class BadViewPager extends ViewPager {

    private int mLastX, mLastY;

    public BadViewPager(@NonNull Context context) {
        super(context);
    }

    public BadViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    // 外部攔截法:父容器處理沖突
    // 我想要把事件分發給誰就分發給誰
    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {

        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                mLastX = (int) event.getX();
                mLastY = (int) event.getY();
                break;
            }
            case MotionEvent.ACTION_MOVE: {
                int deltaX = x - mLastX;
                int deltaY = y - mLastY;
                if (Math.abs(deltaX) > Math.abs(deltaY)) {	//	橫向滑動時攔截
                    return true;
                }
                break;
            }
            case MotionEvent.ACTION_UP: {
                break;
            }
            default:
                break;
        }

        return super.onInterceptTouchEvent(event);

    }
}

內部攔截

ViewPager 代碼

public class BadViewPager extends ViewPager {

    private int mLastX, mLastY;

    public BadViewPager(@NonNull Context context) {
        super(context);
    }

    public BadViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN){
            super.onInterceptTouchEvent(event);
            //	此處是重點
            return false;
        }
        return true;
    }
}

RecyclerView 代碼

public class MyListView extends ListView {

    public MyListView(Context context) {
        super(context);
    }

    public MyListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    // 內部攔截法:子view處理事件沖突
    private int mLastX, mLastY;

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                getParent().requestDisallowInterceptTouchEvent(true);
                break;
            }
            case MotionEvent.ACTION_MOVE: {
                int deltaX = x - mLastX;
                int deltaY = y - mLastY;
                if (Math.abs(deltaX) > Math.abs(deltaY)) {
                    getParent().requestDisallowInterceptTouchEvent(false);
                }
                break;
            }
            case MotionEvent.ACTION_UP: {
                break;

            }
            default:
                break;
        }

        mLastX = x;
        mLastY = y;
        return super.dispatchTouchEvent(event);
    }
}

此處一定要註意,父佈局在 ACTION_DOWN 時一定要返回false。原因如下:

當分發DOWN事件時,執行瞭 resetTouchState(); 函數

    private void resetTouchState() {
        clearTouchTargets();
        resetCancelNextUpFlag(this);
        mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
        mNestedScrollAxes = SCROLL_AXIS_NONE;
    }

mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT

在判斷父佈局攔截時

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

即 mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT & FLAG_DISALLOW_INTERCEPT != 0 ==》false
使用 if 語句永遠是true,在這裡ViewPager會攔截事件,所以RecyclerView無法上下滑動。所以內部攔截時要修改父佈局的 onInterceptTouchEvent 函數!

到此這篇關於Android 深入探究自定義view之事件的分發機制與處理詳解的文章就介紹到這瞭,更多相關Android 自定義view內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: