Android進(jìn)階事件分發(fā)機(jī)制解決事件沖突
引言
相信伙伴們?cè)谌粘5拈_發(fā)工作中,一定會(huì)遇到事件沖突的問題,e.g. 一個(gè)頁面當(dāng)手指滑動(dòng)的時(shí)候,會(huì)翻到下一頁;點(diǎn)擊的時(shí)候,需要響應(yīng)頁面中的元素點(diǎn)擊事件,這個(gè)時(shí)候如果沒有處理滑動(dòng)事件,可能遇到的問題就是在滑動(dòng)翻頁的時(shí)候卻只響應(yīng)了點(diǎn)擊事件,這個(gè)就是點(diǎn)擊事件與滑動(dòng)事件的沖突。其實(shí)還有很多常見的經(jīng)典事件,e.g. RecyclerView嵌套滑動(dòng),ViewPager與RecyclerView嵌套滑動(dòng)等,所以這個(gè)時(shí)候我們需要對(duì)事件分發(fā)非常了解,才能針對(duì)需求做相應(yīng)的處理。
1 Android 事件分發(fā)機(jī)制
這是一個(gè)老生常談的問題,相信伙伴們都了解常見的Android事件類型:ACTION_DOWN、ACTION_MOVE、ACTION_UP,分別代表手指按下屏幕的事件、手指滑動(dòng)的事件以及手指抬起的事件,那么從手指按下到事件響應(yīng),中間經(jīng)歷了什么呢?我們從Google的源碼中去尋找答案。
1.1 事件分發(fā)流程
因?yàn)閷?duì)于組件來說,這個(gè)事件要么消費(fèi)要么不消費(fèi)(事件處理),而對(duì)于容器來說,還需要做的一件事就是分發(fā)事件,通常是先分發(fā)后處理,而View就只是處理事件。
因此在進(jìn)行事件沖突處理的時(shí)候,對(duì)于事件是否向下分發(fā)給子View消費(fèi),就需要在父容器中做攔截,子View僅做事件消費(fèi)。
1.2 View的事件消費(fèi)
首先我們先不看事件是如何分發(fā)的,先關(guān)注下事件是如何被處理的,在View的dispatchTouchEvent方法中,就包含對(duì)事件的處理全過程。
public boolean dispatchTouchEvent(MotionEvent event) { //...... boolean result = false; if (mInputEventConsistencyVerifier != null) { mInputEventConsistencyVerifier.onTouchEvent(event, 0); } final int actionMasked = event.getActionMasked(); if (actionMasked == MotionEvent.ACTION_DOWN) { // Defensive cleanup for new gesture stopNestedScroll(); } if (onFilterTouchEventForSecurity(event)) { if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) { result = true; } //核心代碼1 ListenerInfo li = mListenerInfo; if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && li.mOnTouchListener.onTouch(this, event)) { result = true; } //核心代碼2 if (!result && onTouchEvent(event)) { result = true; } } if (!result && mInputEventConsistencyVerifier != null) { mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); } // Clean up after nested scrolls if this is the end of a gesture; // also cancel it if we tried an ACTION_DOWN but we didn't want the rest // of the gesture. if (actionMasked == MotionEvent.ACTION_UP || actionMasked == MotionEvent.ACTION_CANCEL || (actionMasked == MotionEvent.ACTION_DOWN && !result)) { stopNestedScroll(); } return result; }
看到dispatchTouchEvent,我們可能會(huì)想,這個(gè)方法名看著像是分發(fā)事件的方法,View不是僅僅消費(fèi)事件嗎,還需要處理分發(fā)?其實(shí)不是這樣的,因?yàn)閂iew對(duì)于事件可以有選擇的,可以選擇不處理事件,那么就會(huì)往上派給父類去處理這個(gè)事件,如果能夠消費(fèi),那么就在onTouchEvent中處理了。
核心代碼1:首先拿到一個(gè)ListenerInfo對(duì)象,這個(gè)對(duì)象中標(biāo)記了這個(gè)View設(shè)置的監(jiān)聽事件,這里有幾個(gè)判斷條件:
(1)ListenerInfo不為空,而且設(shè)置了OnTouchListener監(jiān)聽;
(2)設(shè)置了OnTouchListener監(jiān)聽,而且onTouch方法返回了true
這個(gè)時(shí)候,result設(shè)置為true;
核心代碼2:如果滿足了核心代碼1的全部條件,那么核心代碼2就不會(huì)走到onTouchEvent這個(gè)判斷條件中,因?yàn)閞esult = true不滿足條件直接break。
那么如果設(shè)置了OnTouchListener監(jiān)聽,而且onTouch方法返回了false,那么result = false,核心代碼2就能夠執(zhí)行onTouchEvent方法,我們看下這個(gè)方法實(shí)現(xiàn)。
public boolean onTouchEvent(MotionEvent event) { //...... if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) { switch (action) { case MotionEvent.ACTION_UP: mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; if ((viewFlags & TOOLTIP) == TOOLTIP) { handleTooltipUp(); } if (!clickable) { removeTapCallback(); removeLongPressCallback(); mInContextButtonPress = false; mHasPerformedLongPress = false; mIgnoreNextUpEvent = false; break; } boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { // take focus if we don't have it already and we should in // touch mode. boolean focusTaken = false; if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { focusTaken = requestFocus(); } if (prepressed) { // The button is being released before we actually // showed it as pressed. Make it show the pressed // state now (before scheduling the click) to ensure // the user sees it. setPressed(true, x, y); } if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) { // This is a tap, so remove the longpress check removeLongPressCallback(); // Only perform take click actions if we were in the pressed state if (!focusTaken) { // Use a Runnable and post this rather than calling // performClick directly. This lets other visual state // of the view update before click actions start. if (mPerformClick == null) { mPerformClick = new PerformClick(); } if (!post(mPerformClick)) { performClickInternal(); } } } if (mUnsetPressedState == null) { mUnsetPressedState = new UnsetPressedState(); } if (prepressed) { postDelayed(mUnsetPressedState, ViewConfiguration.getPressedStateDuration()); } else if (!post(mUnsetPressedState)) { // If the post failed, unpress right now mUnsetPressedState.run(); } removeTapCallback(); } mIgnoreNextUpEvent = false; break; case MotionEvent.ACTION_DOWN: if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) { mPrivateFlags3 |= PFLAG3_FINGER_DOWN; } mHasPerformedLongPress = false; if (!clickable) { checkForLongClick( ViewConfiguration.getLongPressTimeout(), x, y, TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS); break; } if (performButtonActionOnTouchDown(event)) { break; } // Walk up the hierarchy to determine if we're inside a scrolling container. boolean isInScrollingContainer = isInScrollingContainer(); // For views inside a scrolling container, delay the pressed feedback for // a short period in case this is a scroll. if (isInScrollingContainer) { mPrivateFlags |= PFLAG_PREPRESSED; if (mPendingCheckForTap == null) { mPendingCheckForTap = new CheckForTap(); } mPendingCheckForTap.x = event.getX(); mPendingCheckForTap.y = event.getY(); postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); } else { // Not inside a scrolling container, so show the feedback right away setPressed(true, x, y); checkForLongClick( ViewConfiguration.getLongPressTimeout(), x, y, TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS); } break; //----------注意這里的返回值,clickable為true----------// return true; } //----------注意這里的返回值,clickable為false----------// return false; }
這里就是對(duì)所有事件的處理,包括但不限于ACTION_DOWN、ACTION_UP,我們需要知道一點(diǎn)就是,View的click事件其實(shí)是在ACTION_UP中處理的。我們從上面的源碼中可以看出來,在ACTION_UP中有一個(gè)方法performClickInternal,具體實(shí)現(xiàn)為performClick方法。
public boolean performClick() { // We still need to call this method to handle the cases where performClick() was called // externally, instead of through performClickInternal() notifyAutofillManagerOnClick(); final boolean result; final ListenerInfo li = mListenerInfo; if (li != null && li.mOnClickListener != null) { playSoundEffect(SoundEffectConstants.CLICK); li.mOnClickListener.onClick(this); result = true; } else { result = false; } sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); notifyEnterOrExitForAutoFillIfNeeded(true); return result; }
在這個(gè)方法中,我們貌似看到同樣的一段代碼,如果設(shè)置了OnClickListener監(jiān)聽,那么就會(huì)執(zhí)行onClick方法也就是響應(yīng)點(diǎn)擊事件。
所以通過上面的分析,我們能夠了解,如果同一個(gè)View同時(shí)設(shè)置了setOnClickListener和setOnTouchListener,如果setOnTouchListener返回了false,那么點(diǎn)擊事件是可以響應(yīng)的;如果setOnTouchListener返回了true,那么點(diǎn)擊事件將不再響應(yīng)。
binding.tvHello.setOnClickListener { Log.e("TAG","OnClick") } binding.tvHello.setOnTouchListener(object : View.OnTouchListener{ override fun onTouch(v: View?, event: MotionEvent?): Boolean { Log.e("TAG","onTouch") return false } })
還需要注意一點(diǎn)的就是,對(duì)于clickable這個(gè)屬性要求非常嚴(yán)格,必須要設(shè)置為true才可以進(jìn)行事件的消費(fèi),也就是說在clickable為true的時(shí)候,onTouchEvent才會(huì)返回true,否則就會(huì)返回false,這個(gè)DOWN事件沒有被消費(fèi),也就是說在dispatchTransformedTouchEvent方法中返回了false,此時(shí)就不會(huì)給 mFirstTouchTraget == null 賦值,后續(xù)MOVE事件進(jìn)來就不會(huì)處理,這里需要非常注意。
這里伙伴們?nèi)绻焕斫?,可以換句話說:就是當(dāng)DOWN事件來臨之后,其實(shí)ViewGroup一定會(huì)將事件分發(fā)給子View,看子View要不要消費(fèi),如果子View不是clickable的,也就是說clickable = false,那么此時(shí)子View的onTouchEvent返回false,那么dispatchTouchEvent也是返回false,代表子View不消費(fèi)這個(gè)事件,那么此時(shí)dispatchTransformedTouchEvent也是返回了false,mFirstTouchTraget還是空;因?yàn)?strong>子View沒有消費(fèi)DOWN事件,那么后續(xù)事件不會(huì)再觸發(fā)了。
1.3 ViewGroup的事件分發(fā) -- ACTION_DOWN
前面我們介紹了View對(duì)于事件的消費(fèi),不管是click還是touch,都有對(duì)應(yīng)的標(biāo)準(zhǔn)決定是否能夠響應(yīng)事件,最終View的dispatchTouchEvent返回值,就是result的值,只要有一個(gè)事件被消費(fèi),那么這個(gè)事件就算是到頭了,但是,如果最終事件沒有被消費(fèi),也就是說dispatchTouchEvent返回了false,那么父容器就能夠拿到這個(gè)狀態(tài),決定誰去處理這個(gè)事件。
所以ViewGroup就像是荷官,卡牌就是事件,她可以決定牌發(fā)到誰的手里,所以ViewGroup的事件分發(fā)機(jī)制核心就在于dispatchTouchEvent方法。
public boolean dispatchTouchEvent(MotionEvent ev) { // ...... if (onFilterTouchEventForSecurity(ev)) { final int action = ev.getAction(); final int actionMasked = action & MotionEvent.ACTION_MASK; // Handle an initial down. 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(); } // Check for interception. 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; } // If intercepted, start normal event dispatch. Also if there is already // a view that is handling the gesture, do normal event dispatch. if (intercepted || mFirstTouchTarget != null) { ev.setTargetAccessibilityFocus(false); } // Check for cancelation. final boolean canceled = resetCancelNextUpFlag(this) || actionMasked == MotionEvent.ACTION_CANCEL; // Update list of touch targets for pointer down, if needed. final boolean isMouseEvent = ev.getSource() == InputDevice.SOURCE_MOUSE; final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0 && !isMouseEvent; TouchTarget newTouchTarget = null; boolean alreadyDispatchedToNewTouchTarget = false; // -------- 這里是不攔截的時(shí)候會(huì)走的地方 -------// if (!canceled && !intercepted) { // If the event is targeting accessibility focus we give it to the // view that has accessibility focus and if it does not handle it // we clear the flag and dispatch the event to all children as usual. // We are looking up the accessibility focused host to avoid keeping // state since these events are very rare. View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus() ? findChildWithAccessibilityFocus() : null; if (actionMasked == MotionEvent.ACTION_DOWN || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN) || actionMasked == MotionEvent.ACTION_HOVER_MOVE) { final int actionIndex = ev.getActionIndex(); // always 0 for down final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex) : TouchTarget.ALL_POINTER_IDS; // Clean up earlier touch targets for this pointer id in case they // have become out of sync. removePointersFromTouchTargets(idBitsToAssign); final int childrenCount = mChildrenCount; if (newTouchTarget == null && childrenCount != 0) { final float x = isMouseEvent ? ev.getXCursorPosition() : ev.getX(actionIndex); final float y = isMouseEvent ? ev.getYCursorPosition() : ev.getY(actionIndex); // Find a child that can receive the event. // Scan children from front to back. 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); // If there is a view that has accessibility focus we want it // to get the event first and if not handled we will perform a // normal dispatch. We may do a double iteration but this is // safer given the timeframe. if (childWithAccessibilityFocus != null) { if (childWithAccessibilityFocus != child) { continue; } childWithAccessibilityFocus = null; i = childrenCount - 1; } if (!child.canReceivePointerEvents() || !isTransformedTouchPointInView(x, y, child, null)) { ev.setTargetAccessibilityFocus(false); 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); 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(); newTouchTarget = addTouchTarget(child, idBitsToAssign); 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); } 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; } } } //-------------這里是攔截之后會(huì)走的地方-------------// // 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); } 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; if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) { handled = true; } else { 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; } } // Update list of touch targets for pointer up or cancel, if needed. 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; }
1.1.1 萬事皆始于ACTION_DOWN
看著dispatchTouchEvent這么長的代碼,是不是腦袋都昏了,我給伙伴們分下層,首先一切的事件分發(fā)都是從ACTION_DOWN事件開始,所以我們可以看下ACTION_DOWN事件是如何處理的。
核心代碼1:
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; }
當(dāng)ACTION_DWON事件來了之后,首先調(diào)用ViewGroup的dispatchTouchEvent方法,在上面這段代碼中,就是判斷ViewGroup是否要攔截這個(gè)事件,如果DOWN事件都被攔截了,就沒有小弟的份了。
所以如果當(dāng)前是DOWN事件,或者mFirstTouchTarget不為空。首先這里有一個(gè)變量mFirstTouchTarget,我們可以認(rèn)為這個(gè)就是可能會(huì)消費(fèi)事件的View,因?yàn)槭状慰隙榭?,但是?dāng)前為DOWN事件,所以這個(gè)條件是滿足的,那么就會(huì)進(jìn)入到代碼塊中。
在代碼塊中,有一個(gè)disallowIntercept變量,這個(gè)變量標(biāo)志著子View是否需要消費(fèi)這個(gè)事件,如果需要消費(fèi)這個(gè)事件,子View可以調(diào)用requestDisallowInterceptTouchEvent這個(gè)方法,設(shè)置為true,那么父容器就不會(huì)攔截。
所以如果子View需要消費(fèi)這個(gè)事件,那么disallowIntercept = true,這個(gè)時(shí)候intercepted = false,意味著父容器不會(huì)攔截;如果子View不消費(fèi)這個(gè)事件,那么disallowIntercept = false,然后會(huì)判斷ViewGroup中的onInterceptTouchEvent方法,是否由父容器消費(fèi)這個(gè)事件從而決定intercepted的值。
所以看到這里,其實(shí)我們?cè)诮鉀Q事件沖突的時(shí)候就會(huì)有兩種方式:一種就是重寫父容器的onInterceptTouchEvent方法,由父容器決定是否攔截;另一種就是由子View調(diào)用requestDisallowInterceptTouchEvent方法,通知父容器是否能夠攔截。
那么假設(shè),當(dāng)前ViewGroup要攔截這個(gè)事件,也就是在onInterceptTouchEvent中返回了true
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean { return true }
1.1.2 ViewGroup攔截事件
那么既然攔截了事件,那么當(dāng)前ViewGroup就需要決定到底處不處理事件,如果不處理就需要向上傳遞。
因?yàn)閂iewGroup攔截了事件,因此intercepted = true,在1.3開頭的代碼中,我標(biāo)記了2個(gè)位置,一個(gè)是攔截會(huì)走的位置,一個(gè)是沒有攔截會(huì)走的位置。
核心代碼2:
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; if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) { handled = true; } else { 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; } }
因?yàn)檫@個(gè)時(shí)候,mFirstTouchTarget還是為空的,所以會(huì)調(diào)用dispatchTransformedTouchEvent方法。
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel, View child, int desiredPointerIdBits) { final boolean handled; // ...... // Perform any necessary transformations and dispatch. 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); } // Done. transformedEvent.recycle(); return handled; }
這時(shí)候需要注意一點(diǎn),這個(gè)方法第三個(gè)參數(shù)為null; 所以當(dāng)child為空的時(shí)候,就會(huì)調(diào)用父類的dispatchTouchEvent,也就是View的dispatchTouchEvent方法,在1.2小節(jié)中我們是對(duì)這個(gè)方法做過分析的,也是會(huì)決定是否處理這個(gè)事件,最終返回是否處理的結(jié)果。
所以這一次的結(jié)果(handled的值)最終決定了當(dāng)前ViewGroup是否會(huì)處理這個(gè)事件,如果不處理,那么就扔到上級(jí)再判斷。
1.1.3 ViewGroup不攔截事件
如果ViewGroup不攔截事件,那么intercepted = false,所以會(huì)走到分發(fā)事件的代碼中。
核心代碼3:
if (!canceled && !intercepted) { if (actionMasked == MotionEvent.ACTION_DOWN || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN) || actionMasked == MotionEvent.ACTION_HOVER_MOVE) { final int actionIndex = ev.getActionIndex(); // always 0 for down final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex) : TouchTarget.ALL_POINTER_IDS; // Clean up earlier touch targets for this pointer id in case they // have become out of sync. removePointersFromTouchTargets(idBitsToAssign); final int childrenCount = mChildrenCount; if (newTouchTarget == null && childrenCount != 0) { final float x = isMouseEvent ? ev.getXCursorPosition() : ev.getX(actionIndex); final float y = isMouseEvent ? ev.getYCursorPosition() : ev.getY(actionIndex); // Find a child that can receive the event. // Scan children from front to back. 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); // If there is a view that has accessibility focus we want it // to get the event first and if not handled we will perform a // normal dispatch. We may do a double iteration but this is // safer given the timeframe. if (childWithAccessibilityFocus != null) { if (childWithAccessibilityFocus != child) { continue; } childWithAccessibilityFocus = null; i = childrenCount - 1; } //-----判斷View是否有消費(fèi)的可能性---------// if (!child.canReceivePointerEvents() || !isTransformedTouchPointInView(x, y, child, null)) { ev.setTargetAccessibilityFocus(false); 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); //-------- 這個(gè)方法需要注意,第三個(gè)參數(shù)不為空----------// 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(); newTouchTarget = addTouchTarget(child, idBitsToAssign); 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); } 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; } } }
這里首先會(huì)判斷事件是否為down事件,只有down事件才會(huì)分發(fā),如果是move或者up事件便不會(huì)分發(fā)。所以伙伴們需要牢記一點(diǎn),如果在某個(gè)控件上產(chǎn)生了up事件,即便是設(shè)置了onClickListener,因?yàn)闆]有接收到down事件,所以也不會(huì)響應(yīng)點(diǎn)擊事件。
然后調(diào)用buildTouchDispatchChildList方法,對(duì)當(dāng)前ViewGroup全部的子View根據(jù)Z軸順序排序,
ArrayList<View> buildOrderedChildList() { final int childrenCount = mChildrenCount; if (childrenCount <= 1 || !hasChildWithZ()) return null; if (mPreSortedChildren == null) { mPreSortedChildren = new ArrayList<>(childrenCount); } else { // callers should clear, so clear shouldn't be necessary, but for safety... mPreSortedChildren.clear(); mPreSortedChildren.ensureCapacity(childrenCount); } final boolean customOrder = isChildrenDrawingOrderEnabled(); for (int i = 0; i < childrenCount; i++) { // add next child (in child order) to end of list final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder); final View nextChild = mChildren[childIndex]; final float currentZ = nextChild.getZ(); // insert ahead of any Views with greater Z int insertIndex = i; while (insertIndex > 0 && mPreSortedChildren.get(insertIndex - 1).getZ() > currentZ) { insertIndex--; } mPreSortedChildren.add(insertIndex, nextChild); } return mPreSortedChildren; }
這里我們可以看到是按照Z軸值從高到低排序,Z值越大,說明其層級(jí)越深,最終拿到一個(gè)View的集合。
然后遍歷取值的時(shí)候,是按照倒序取值的方式,因?yàn)閆值越小,說明其層級(jí)越淺,事件被消費(fèi)的概率就越高;取出一個(gè)View之后,首先需要判斷它是否具備消費(fèi)事件的可能性。
if (!child.canReceivePointerEvents() || !isTransformedTouchPointInView(x, y, child, null)) { ev.setTargetAccessibilityFocus(false); continue; }
第一個(gè)條件:View是可見的,或者 getAnimation() != null
protected boolean canReceivePointerEvents() { return (mViewFlags & VISIBILITY_MASK) == VISIBLE || getAnimation() != null; }
第二個(gè)條件:當(dāng)前View在點(diǎn)擊(x,y)的范圍之內(nèi),如果離著手指點(diǎn)擊的位置很遠(yuǎn),肯定不可能消費(fèi)。
protected boolean isTransformedTouchPointInView(float x, float y, View child, PointF outLocalPoint) { final float[] point = getTempLocationF(); point[0] = x; point[1] = y; transformPointToViewLocal(point, child); final boolean isInView = child.pointInView(point[0], point[1]); if (isInView && outLocalPoint != null) { outLocalPoint.set(point[0], point[1]); } return isInView; }
所以經(jīng)過層層篩選,也就只剩下一小部分可能會(huì)消費(fèi)事件的View,那么怎么把他揪出來呢?經(jīng)過篩選的View最終調(diào)用了dispatchTransformedTouchEvent方法,在1.1.2中我們介紹了這個(gè)方法,就是用來判斷是否消費(fèi)事件的,這里傳入的第三個(gè)參數(shù)不為空!
回到前面dispatchTransformedTouchEvent方法中,當(dāng)child不為空的時(shí)候,走到else代碼塊中,最終還是調(diào)用了child的dispatchTouchEvent方法。
所以如果當(dāng)前View消費(fèi)了DOWN事件,那么返回值為true,也就是dispatchTransformedTouchEvent返回了true,那么會(huì)進(jìn)入下面代碼塊中。
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; }
因?yàn)楫?dāng)前child消費(fèi)了事件,那么我們前面提到的mFirstTouchTarget就是由child封裝一層得來的,也就是調(diào)用了addTouchTarget方法,也就是說當(dāng)一個(gè)child消費(fèi)了一個(gè)DOWN事件之后,mFirstTouchTarget就不再為空了。
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) { final TouchTarget target = TouchTarget.obtain(child, pointerIdBits); target.next = mFirstTouchTarget; mFirstTouchTarget = target; return target; }
如果全部都不處理,那么mFirstTouchTarget還是為空,走到下面還是會(huì)執(zhí)行ViewGroup攔截事件的邏輯,也就是1.1.2中的邏輯,所以說,如果全部的子View都不處理,其實(shí)跟ViewGroup攔截事件的本質(zhì)是一致的。
1.4 ViewGroup的事件分發(fā) -- ACTION_MOVE
前面我們介紹了ViewGroup對(duì)于ACTION_DOWN事件的分發(fā)處理,因?yàn)镈OWN事件只有一次,MOVE可以有無數(shù)次,所以在處理完DOWN事件之后,就會(huì)有MOVE事件涌進(jìn)來。
所以還是回到前面的判斷條件中,我們對(duì)于MOVE事件的分發(fā),需要基于DOWN事件的處理;
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; }
如果ViewGroup攔截了事件:
那么mFirstTouchTarget == null,會(huì)走到else中,此時(shí) intercepted = true,那么就會(huì)走到ViewGroup攔截邏輯中,會(huì)調(diào)用dispatchTransformedTouchEvent,第三個(gè)參數(shù)child == null,那么如果ViewGroup不消費(fèi)不處理,就會(huì)交給上級(jí)處理。
如果ViewGroup不攔截事件:
那么mFirstTouchTarget != null,此時(shí)還是會(huì)判斷子View是否攔截該事件,如果攔截,那么intercepted = true,還是會(huì)走上面的攔截邏輯;如果不攔截,那么intercepted = false,會(huì)走到ViewGroup不攔截事件的邏輯中。
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; }
因?yàn)?strong>只有DOWN事件的時(shí)候,才會(huì)遍歷View樹,如果是MOVE事件,不會(huì)進(jìn)入循環(huán),不再分發(fā),而是走上面的邏輯,此時(shí)newTouchTarget == null 而且 mFirstTouchTarget不為空,此時(shí)會(huì)給newTouchTarget重新賦值,然后繼續(xù)往下走。
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; if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) { handled = true; } else { 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; } }
因?yàn)閙FirstTouchTarget != null,因此會(huì)走到else代碼塊中,因?yàn)閍lreadyDispatchedToNewTouchTarget是在事件分發(fā)時(shí)才賦值為true,所以在while循環(huán)中(一次循環(huán),單點(diǎn)觸控),會(huì)走else代碼塊,其實(shí)還是會(huì)調(diào)用dispatchTransformedTouchEvent方法判斷是否處理事件,所以這就形成了一條責(zé)任鏈,當(dāng)一個(gè)View消費(fèi)了DOWN事件之后,后續(xù)的事件系統(tǒng)默認(rèn)都會(huì)給他消費(fèi),除非特殊情況。
2 Android事件沖突處理
基于Android事件分發(fā)機(jī)制,DOWN事件只會(huì)執(zhí)行一次,而且只是做分發(fā)工作,而MOVE事件會(huì)有無數(shù)次,所以對(duì)于事件沖突來說,只能在MOVE事件中進(jìn)行處理。
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; }
針對(duì)這種分發(fā)機(jī)制,前面也提到了兩種處理方式,要么在父容器的onInterceptTouchEvent中判斷是否攔截事件,要么控制disallowIntercept的值,所以就出現(xiàn)了2種攔截法。
2.1 內(nèi)部攔截法
此方式指的是在子View中,通過控制disallowIntercept的值,來讓父容器決定是否攔截事件。
class MotionEventLayout( val mContext: Context, val attrs: AttributeSet? = null, val defStyleAttr: Int = 0 ) : FrameLayout(mContext, attrs, defStyleAttr) { override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean { return true } }
如果在父容器的onInterceptTouchEvent方法中返回true,那么down一定會(huì)被攔截而不會(huì)分發(fā)給子View,所以子View不會(huì)響應(yīng)任何事件。
class MotionEventChildLayout( val mContext: Context, val attrs: AttributeSet? = null, val defStyleAttr: Int = 0 ) : FrameLayout(mContext, attrs, defStyleAttr) { private var startX = 0 private var startY = 0 override fun dispatchTouchEvent(ev: MotionEvent?): Boolean { when (ev?.action) { MotionEvent.ACTION_DOWN -> { //不能被攔截 parent.requestDisallowInterceptTouchEvent(true) } MotionEvent.ACTION_MOVE -> { var endX = ev.rawX var endY = ev.rawY //豎向滑動(dòng) if (abs(endX - startX) > abs(endY - startY)) { parent.requestDisallowInterceptTouchEvent(false) } startX = endX startY = endY } } return super.dispatchTouchEvent(ev) } }
所以使用內(nèi)部攔截法時(shí),對(duì)于DOWN事件不能被攔截,需要將requestDisallowInterceptTouchEvent設(shè)置為true,這樣父容器在分發(fā)事件時(shí),就不會(huì)走自身的onInterceptTouchEvent方法(此時(shí)無論設(shè)置true或者false都是無效的),intercepted = false,此時(shí)事件就會(huì)被分發(fā)到子View。
然后在滑動(dòng)時(shí),如果父容器支持左右滑動(dòng),子View支持上下滑動(dòng),那么就可以判斷:如果橫向滑動(dòng)的距離大于豎直方向滑動(dòng)的距離,任務(wù)在左右滑動(dòng),此時(shí)事件處理交給父容器處理;反之則交給子View處理。
這是我們理解中的處理方式,看著好像沒問題,但是實(shí)際運(yùn)行時(shí)發(fā)現(xiàn)無效!! 我們明明設(shè)置了requestDisallowInterceptTouchEvent為true,為什么沒生效呢?
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(); }
通過源碼我們發(fā)現(xiàn),當(dāng)DOWN事件觸發(fā)之后,會(huì)清除所有的標(biāo)志位,包括disallowIntercept,所以在使用內(nèi)部攔截法的時(shí)候,我們需要保證外部容器不能攔截DOWN事件,其實(shí)這個(gè)不會(huì)有問題的,大不了所有的子View都不處理,最終再扔給你處理。
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean { if (ev?.action == MotionEvent.ACTION_DOWN) { super.onInterceptTouchEvent(ev) return false } return true }
所以在父容器的onInterceptTouchEvent方法中,不能對(duì)DOWN事件進(jìn)行攔截,這里返回了false。
因?yàn)楦溉萜鳑]有攔截down事件,所以事件被分發(fā)給了子View(可以上下滑動(dòng)),緊接著MOVE事件來了,全部交給了子View處理,這時(shí)的mFirstTouchTarget還是子View的。如果用戶手勢改成了左右滑動(dòng),那么這個(gè)過程兩者是如何完成轉(zhuǎn)換的呢?
此時(shí),mFirstTouchTarget != null,action == MOVE,disallowIntercept = false,因?yàn)槭莔ove事件,所有標(biāo)志位不會(huì)被清除,此時(shí)會(huì)走到這里。
if (!disallowIntercept) { intercepted = onInterceptTouchEvent(ev); ev.setAction(action); // restore action in case it was changed }
此時(shí),父容器的onInterceptTouchEvent返回的是true,要攔截子View的事件了,此時(shí)intercepted = true,因?yàn)閙FirstTouchTarget != null,所以在攔截邏輯里,是會(huì)走到else代碼塊中的。
while (target != null) { final TouchTarget next = target.next; if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) { handled = true; } else { 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; }
因?yàn)檫@個(gè)時(shí)候 intercepted = true,所以cancelChild = true,所以在dispatchTransformedTouchEvent方法中,第二個(gè)參數(shù)為true。
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel, View child, int desiredPointerIdBits) { final boolean handled; // Canceling motions is a special case. We don't need to perform any transformations // or filtering. The important part is the action, not the contents. final int oldAction = event.getAction(); if (cancel || oldAction == MotionEvent.ACTION_CANCEL) { event.setAction(MotionEvent.ACTION_CANCEL); if (child == null) { handled = super.dispatchTouchEvent(event); } else { handled = child.dispatchTouchEvent(event); } event.setAction(oldAction); return handled; } }
這時(shí)會(huì)觸發(fā)一個(gè)ACTION_CANCEL事件,這個(gè)事件是子View事件被上層攔截的時(shí)候觸發(fā)的,其實(shí)當(dāng)前這個(gè)MOVE事件做的一件事,就是執(zhí)行了子View的cancel事件,然后將mFirstTouchTarget置為了空;因?yàn)镸OVE事件很多,所以下個(gè)MOVE事件進(jìn)來之后,又會(huì)走到判斷是否攔截的邏輯中。
此時(shí)父容器會(huì)冷酷地?cái)r截這些MOVE事件,原本屬于子View的MOVE事件,而且不會(huì)往下分發(fā),走到攔截邏輯中,因?yàn)榇藭r(shí)mFirstTouchTarget為空,所以直接由自身決定是否消費(fèi),肯定消費(fèi)了,因?yàn)樵谧笥一瑒?dòng),也就是這樣完成的事件消費(fèi)處理權(quán)的切換。
2.2 外部攔截法
那么對(duì)于外部攔截法,則是需要?jiǎng)討B(tài)修改onInterceptTouchEvent的返回值,如果用戶左右滑動(dòng),那么就攔截,onInterceptTouchEvent返回true,此時(shí)intercepted = true,就不再走事件分發(fā)流程了。
class MotionEventLayout( val mContext: Context, val attrs: AttributeSet? = null, val defStyleAttr: Int = 0 ) : FrameLayout(mContext, attrs, defStyleAttr) { private var startX = 0f private var startY = 0f override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean { var intercepted = false when (ev?.action) { MotionEvent.ACTION_DOWN -> { } MotionEvent.ACTION_MOVE -> { val endX = ev.rawX val endY = ev.rawY //豎向滑動(dòng) intercepted = abs(endX - startX) > abs(endY - startY) startX = endX startY = endY } } return intercepted } }
相較于內(nèi)部攔截法,外部攔截就顯得比較簡單了,完全由父容器發(fā)牌決定。
以上就是Android進(jìn)階事件分發(fā)機(jī)制解決事件沖突的詳細(xì)內(nèi)容,更多關(guān)于Android事件沖突解決的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vscode通過wifi調(diào)試真機(jī)的Flutter應(yīng)用的教程
這篇文章主要介紹了vscode通過wifi調(diào)試真機(jī)的Flutter應(yīng)用的教程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04Android使用Intent.ACTION_SEND分享圖片和文字內(nèi)容的示例代碼
這篇文章主要介紹了Android使用Intent.ACTION_SEND分享圖片和文字內(nèi)容的示例代碼的實(shí)例代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,一起跟隨小編過來看看吧2018-05-05Android 仿小米鎖屏實(shí)現(xiàn)九宮格解鎖功能(無需圖片資源)
最近公司要求做個(gè)九宮格解鎖,本人用的是小米手機(jī),看著他那個(gè)設(shè)置鎖屏九宮格很好看,就做了該組件,不使用圖片資源,純代碼實(shí)現(xiàn),感興趣的朋友參考下吧2016-12-12Android Fragment的靜態(tài)注冊(cè)和動(dòng)態(tài)注冊(cè)創(chuàng)建步驟
這篇文章主要介紹了Android Fragment的靜態(tài)注冊(cè)和動(dòng)態(tài)注冊(cè)創(chuàng)建步驟,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02Android中FontMetrics的幾個(gè)屬性全面講解
下面小編就為大家?guī)硪黄狝ndroid中FontMetrics的幾個(gè)屬性全面講解。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-11-11Android Jetpack架構(gòu)組件Lifecycle詳解
這篇文章主要介紹了Android Jetpack架構(gòu)組件Lifecycle詳解,Lifecycle是Jetpack架構(gòu)組件中用來感知生命周期的組件,使用Lifecycles可以幫助我們寫出和生命周期相關(guān)更簡潔更易維護(hù)的代碼。對(duì)此感興趣的小伙伴可以來學(xué)習(xí)一下2020-07-07