您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關Android中自定義view中事件分發機制與處理的示例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
事件只有一個,多個人想要處理,處理的對象不是我們想給的對象就是事件沖突。
如上圖,RecyclerView 的父布局是ViewPager,左右滑動時沒問題,上下滑動時RecyclerView好像沒收到滑動事件一樣,無法達到我們預期的效果。我們的觸摸被封裝成MotionEvent事件傳遞,在多個層級中它是如何傳遞的呢?又是根據什么來確定哪個view處理這個事件的呢,咱們抽絲剝繭一步步揭開她的面紗!
追溯本源,尋找事件分發的開始。
當一個點擊操作發生時,事件最先傳遞給當前的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
進入 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后的滑動,這是個連續的過程
手指點擊后開始滑動,繼續分發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
進入 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); }
分析上面干了啥
從最上層的子view開始往內層遍歷
判斷當前的view在位置上是否滿足觸點位置
調用 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 事件結束
繼上面點擊后開始滑動
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中事件分發機制與處理的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。