您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)Android中自定義view中事件分發(fā)機制與處理的示例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
事件只有一個,多個人想要處理,處理的對象不是我們想給的對象就是事件沖突。
如上圖,RecyclerView 的父布局是ViewPager,左右滑動時沒問題,上下滑動時RecyclerView好像沒收到滑動事件一樣,無法達(dá)到我們預(yù)期的效果。我們的觸摸被封裝成MotionEvent事件傳遞,在多個層級中它是如何傳遞的呢?又是根據(jù)什么來確定哪個view處理這個事件的呢,咱們抽絲剝繭一步步揭開她的面紗!
追溯本源,尋找事件分發(fā)的開始。
當(dāng)一個點擊操作發(fā)生時,事件最先傳遞給當(dāng)前的Activity,由Activity的dispatchTouchEvent進(jìn)行分發(fā)
public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { onUserInteraction(); } if (getWindow().superDispatchTouchEvent(ev)) { return true; } return onTouchEvent(ev); }
這里的getWindow返回的window類只有一個實現(xiàn),PhoneWindow
private DecorView mDecor public boolean superDispatchTouchEvent(MotionEvent event) { return mDecor.superDispatchTouchEvent(event); }
我們繼續(xù)看 DecorView的superDispatchTouchEvent方法實現(xiàn)
public boolean superDispatchTouchEvent(MotionEvent event) { return super.dispatchTouchEvent(event); }
DecorView 繼承于 ViewGroup。此時應(yīng)該理解了,Activity 的 事件分發(fā)交給了 DecorView 處理,而 DecorView 又是什么
DecorView是activity窗口的根視圖,是一個FrameLayout,DecorView內(nèi)部又分為兩部分,一部分是ActionBar,另一部分是ContentParent,即activity在setContentView對應(yīng)的布局。如此一來,事件分發(fā)從系統(tǒng)層面開始向我們寫的布局分發(fā)事件!
事件分發(fā)是一個遞歸的過程,主要涉及三個函數(shù)
dispatchTouchEvent
onInterceptTouchEvent
onTouchEvent
三者關(guān)系
public boolean dispatchTouchEvent(MotionEvent ev){ boolean result = false; if(onInterceptTouchEvent(ev)){ // 如果攔截則交給自己的 onTouchEvent 處理事件 result = onTouchEvent(ev); }else{ // 如果不攔截,交給子布局分發(fā),這是個層層遞歸過程 result = chlid.dispatchTouchEvent(ev); } return result; }
直接擼源碼是一件很痛苦的事情,多種可能的發(fā)生讓源碼可讀性很差。下面我們會從某一種特定邏輯下分析,這樣會清晰很多。每次只分析一種情境!
父布局?jǐn)r截我們分兩步,ACTION_DOWN、ACTION_MOVE
進(jìn)入 ViewGroup 的 dispatchTouchEvent 方法內(nèi)
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 事件,先清空狀態(tài),一個是TouchTarget的狀態(tài),一個是 mGroupFlags。這個用不到繼續(xù)走
// Check for interception. final boolean intercepted; // 因為是第一次過來 mFirstTouchTarget = null ,且是 ACTION_DOWN 事件,走入 if 內(nèi) if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) { // 咱們走的是父布局?jǐn)r截事件,子布局用尚方寶劍,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分發(fā)都進(jìn)不去
// intercepted = true , 進(jìn)不去 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 函數(shù),第三個參數(shù)是 null
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel, View child, int desiredPointerIdBits) { final boolean handled; if (child == null) { // ===== 執(zhí)行位置 ==== 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); } }
第三個參數(shù)傳的是 null ,即 child = null 。調(diào)用 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; }
我們可以得出結(jié)論:onTouch 比 onTouchEvent 優(yōu)先級高,如果onTouch 攔截事件則 onTouchEvent 無法接到事件。這也是為什么我們在onTouch方法返回true后onClick事件失效的原因。onTouchEvent 的邏輯比較簡單,此處不做分析
這里要說明一點,事件分發(fā)機制的分發(fā)其實有兩種含義。一是事件在不同view之間的分發(fā),父布局到子布局的分發(fā);二是事件在view中對不同監(jiān)聽的分發(fā),onTouch、onClick、onLongClick 在分發(fā)時也是有順序的。
到這里父布局?jǐn)r截的DOWN事件算結(jié)束了,下面是MOVE事件,繼DOWN后的滑動,這是個連續(xù)的過程
手指點擊后開始滑動,繼續(xù)分發(fā)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 , 進(jìn)不去 if (!canceled && !intercepted) { for (int i = childrenCount - 1; i >= 0; i--) { } }
同樣的分發(fā)子view的模塊我們依舊進(jìn)不去
// 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); }
到這里就跟之前的邏輯完全一樣了,至此父布局的攔截過程結(jié)束
總結(jié):
ViewGroup 的 onTouchEvent 方法直接調(diào)用父類(View)的實現(xiàn)
父布局一旦攔截Down事件,后續(xù)的move事件都直接由父布局執(zhí)行
這么分析的好處是咱們的狀態(tài)是確定的,分析代碼不會有太多可能性搞亂邏輯,下面是父布局不攔截的情況下事件分發(fā)
父布局不攔截,咱們按照正常流程走一遍,還是按上面那個思路,先 down 后 move
進(jìn)入 GroupView 的 dispatchTouchEvent 方法后依舊西先是清空狀態(tài),然后判斷當(dāng)前布局是否攔截
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; }
咱們的設(shè)定是不攔截,所以 intercepted = false。下面是遍歷子view的代碼
final View[] children = mChildren; for (int i = childrenCount - 1; i >= 0; i--) { final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder); // 逆序拿到一個 child ,即從最上層的子view開始往內(nèi)層遍歷 final View child = getAndVerifyPreorderedView(preorderedList, children, childIndex); // 判斷觸點的位置是否在view的范圍之內(nèi)或者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 函數(shù)是處理分發(fā)的函數(shù),父布局處理用的也是這個 // 如果子view消費了事件則給標(biāo)志位賦值,并 break 結(jié)束循環(huán),如果沒有消費則繼續(xù)循環(huán)尋找分發(fā) 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開始往內(nèi)層遍歷
判斷當(dāng)前的view在位置上是否滿足觸點位置
調(diào)用 dispatchTransformedTouchEvent 判斷是否子view消費了事件
如果消費了事件則記錄 mFirstTouchTarget 和標(biāo)志位,并跳出循環(huán)
如果沒有沒有消費事件則繼續(xù)循環(huán)
注釋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()); } // ===== 執(zhí)行位置 ==== handled = child.dispatchTouchEvent(transformedEvent); } }
這次過來 child != null ,調(diào)用的是 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 事件結(jié)束
繼上面點擊后開始滑動
if (actionMasked == MotionEvent.ACTION_DOWN) { cancelAndClearTouchTargets(ev); resetTouchState(); }
move事件不會重置,繼續(xù)走
if (actionMasked == MotionEvent.ACTION_DOWN|| mFirstTouchTarget != null)
記得down事件中給mFirstTouchTarget 賦過值嘛,雖然不是down事件依舊可以進(jìn)入此方法。也就是說這里依舊會判斷父布局是否要攔截子view,這里也是以后咱們處理事件沖突的重點。當(dāng)前的邏輯是不攔截,所以 intercepted = false
if (actionMasked == MotionEvent.ACTION_DOWN || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN) || actionMasked == MotionEvent.ACTION_HOVER_MOVE)
只有ACTION_DOWN事件才會進(jìn)行分發(fā),所以不會進(jìn)入遍歷子view的邏輯代碼!MOVE事件不會分發(fā)事件!
// 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 { // 此處的結(jié)果是 false final boolean cancelChild = resetCancelNextUpFlag(target.child)|| intercepted; // 在這里被分發(fā)處理 child就是我們要分發(fā)的對象 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 在每次進(jìn)來時都會重置為 false ,最后又會調(diào)用 dispatchTransformedTouchEvent 處理分發(fā)
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()); } // 遞歸調(diào)用它來分發(fā) handled = child.dispatchTouchEvent(transformedEvent); }
至此move事件也結(jié)束,做個總結(jié)
DOWN 事件是事件分發(fā),尋找接盤的 child 并保存在 mFirstTouchTarget 中
MOVE 事件雖然不需要遍歷尋找接盤的view,但還可以被ViewGroup攔截的(比如ViewPager包裹著RecyclerView,DOWN事件時被RecyclerView攔截,橫向滑動時被拋棄,這時候ViewPager是可以攔截橫向滑動接盤的)
滑動沖突解決方案有兩種:內(nèi)部攔截、外部攔截。顧名思義,內(nèi)部攔截是在子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); } // 外部攔截法:父容器處理沖突 // 我想要把事件分發(fā)給誰就分發(fā)給誰 @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); } // 內(nèi)部攔截法:子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。原因如下:
當(dāng)分發(fā)DOWN事件時,執(zhí)行了 resetTouchState(); 函數(shù)
private void resetTouchState() { clearTouchTargets(); resetCancelNextUpFlag(this); mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT; mNestedScrollAxes = SCROLL_AXIS_NONE; }
mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT
在判斷父布局?jǐn)r截時
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 語句永遠(yuǎn)是true,在這里ViewPager會攔截事件,所以RecyclerView無法上下滑動。所以內(nèi)部攔截時要修改父布局的 onInterceptTouchEvent 函數(shù)!
關(guān)于“Android中自定義view中事件分發(fā)機制與處理的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。