責任鏈模式是一種行爲模式,爲請求建立一個接收者的對象鏈.這樣就避免,一個請求連接多個接收者的狀況.進行外部解耦.相似於單向鏈表結構。css
1. 下降耦合度。它將請求的發送者和接收者解耦。app
2. 簡化了對象。使得對象不須要知道鏈的結構。ide
3. 加強給對象指派職責的靈活性。經過改變鏈內的成員或者調動它們的次 序,容許動態地新增或者刪除責任。oop
4. 增長新的請求處理類很方便。post
1. 不能保證請求必定被接收。性能
2. 系統性能將受到必定影響,並且在進行代碼調試時不太方便,可能會形成循環調用。ui
3. 可能不容易觀察運行時的特徵,有礙於除錯。this
通常咱們理解的事件分發的模式以下(傳統模式):spa
使用責任鏈模式直接將message丟到鏈中,讓他們本身匹配.設計
a). 事件收集以後最早傳遞給 Activity, 而後依次向下傳遞,大體以下:
Activity -> PhoneWindow -> DecorView -> ViewGroup -> ... -> View
這樣的事件分發機制邏輯很是清晰,但是,你是否注意到一個問題?若是最後分發到View,若是這個View也沒有處理事件怎麼辦,就這樣讓事件浪費掉?固然不會啦。
b). 若是沒有任何View消費掉事件,那麼這個事件會按照反方向回傳,最終傳回給Activity,若是最後 Activity 也沒有處理,本次事件纔會被拋棄:
Activity <- PhoneWindow <- DecorView <- ViewGroup <- ... <- View
能夠看到,這是一個很是經典的責任鏈模式,若是我能處理就攔截下來本身幹,若是本身不能處理或者不肯定就交給責任鏈中下一個對象。 這種設計是很是精巧的,上層View既能夠直接攔截該事件,本身處理,也能夠先詢問(分發給)子View,若是子View須要就交給子View處理,若是子View不須要還能繼續交給上層View處理。既保證了事件的有序性,又很是的靈活。
View點擊事件分發有三個關鍵流程方法:
1.dispatchTouchEvent
:事件下發 --- View和ViewGroup都有的方法
2.onInterceptTouchEvent
:攔截下發的事件,並交給本身OnTouchEvent
處理處理 ---ViewGroup纔有的方法
3.onTouchEvent
:事件上報 --- View和ViewGroup都有的方法
如下是不一樣層級對事件的分發、攔截和消費的功能表:
能夠看到 Activity 和 View 都是沒有事件攔截的:
a). Activity 做爲原始的事件分發者,若是 Activity 攔截了事件會致使整個屏幕都沒法響應事件,這確定不是咱們想要的效果。
b). View最爲事件傳遞的最末端,要麼消費掉事件,要麼不處理進行回傳,根本不必進行事件攔截。
下圖是點擊View,事件傳遞可是都沒有被處理,生成的一個完整的事件分發流程圖:
若是事件被View處理了,那麼事件分發流程圖應該以下:
若是事件被ViewGroup攔截處理了, 那麼事件分發流程圖應該以下:
從上面的流程,咱們能夠歸納Android的事件分發機制爲:責任鏈模式,事件層層傳遞,直到被消費。
上面咱們講解了一下Android的事件分發機制,可能不少人會有疑惑,下面咱們針對部分疑惑進行分析和說明:
答:咱們知道 View 能夠註冊不少事件監聽器,例如:單擊事件(onClick)、長按事件(onLongClick)、觸摸事件(onTouch),而且View自身也有 onTouchEvent 方法,那麼問題來了,這麼多與事件相關的方法應該由誰管理?毋庸置疑就是 dispatchTouchEvent
,因此 View 也會有事件分發。
View的dispatchTouchEvent源碼:
/** * Pass the touch screen motion event down to the target view, or this * view if it is the target. * * @param event The motion event to be dispatched. * @return True if the event was handled by the view, false otherwise. */ public boolean dispatchTouchEvent(MotionEvent event) { // If the event should be handled by accessibility focus first. if (event.isTargetAccessibilityFocus()) { // We don't have focus or no virtual descendant has it, do not handle the event. if (!isAccessibilityFocusedViewOrHost()) { return false; } // We have focus and got the event, then use normal event dispatch. event.setTargetAccessibilityFocus(false); } 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; } //noinspection SimplifiableIfStatement 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; } } 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; }
a). 單擊事件(onClickListener) 須要兩個兩個事件(ACTION_DOWN 和 ACTION_UP )才能觸發,若是先分配給onClick判斷,等它判斷完再交由其餘相應時間顯然是不合理的,會形成 View 沒法響應其餘事件,應該最後調用。(因此此調用順序最後)
b). 長按事件(onLongClickListener) 同理,也是須要長時間等待才能出結果,確定不能排到前面,但由於不須要ACTION_UP,應該排在 onClick 前面。(onLongClickListener > onClickListener)
c). 觸摸事件(onTouchListener) 若是用戶註冊了觸摸事件,說明用戶要本身處理觸摸事件了,這個應該排在最前面。(最前)
d). View自身處理(onTouchEvent) 提供了一種默認的處理方式,若是用戶已經處理好了,也就不須要了,因此應該排在 onClickListener 後面。(onTouchListener > onClickListener)
因此事件的調度順序應該是 onTouchListener > onTouchEvent > onLongClickListener > onClickListener
。
在默認的狀況下 ViewGroup 事件分發流程是這樣的。
a). 判斷自身是否須要(詢問 onInterceptTouchEvent 是否攔截),若是須要,調用本身的 onTouchEvent。
b). 自身不須要或者不肯定,則詢問 ChildView ,通常來講是調用手指觸摸位置的 ChildView。
c). 若是子 ChildView 不須要則調用自身的 onTouchEvent。
ViewGroup的dispatchTouchEvent源碼:
@Override public boolean dispatchTouchEvent(MotionEvent ev) { if (mInputEventConsistencyVerifier != null) { mInputEventConsistencyVerifier.onTouchEvent(ev, 1); } // If the event targets the accessibility focused view and this is it, start // normal event dispatch. Maybe a descendant is what will handle the click. if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) { ev.setTargetAccessibilityFocus(false); } boolean handled = false; 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 split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0; TouchTarget newTouchTarget = null; boolean alreadyDispatchedToNewTouchTarget = false; 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 = ev.getX(actionIndex); final float y = 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 (!canViewReceivePointerEvents(child) || !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; } } } // 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; }
ViewGroup分發事件時會遍歷 ChildView,若是手指觸摸的點在 ChildView 區域內就分發給這個View。當 ChildView 重疊時,通常會分配給顯示在最上面的 ChildView。
事件優先給 ChildView,會被 ChildView消費掉,ViewGroup 不會響應。