編輯:關於Android編程
這一節才是真正的從源碼的角度去分析View的事件分發機制,結合第一篇去看,理解會更深刻。首先,要明白我們分析的對象就是MotionEvent,它包括三種典型的事件類型:
ACTION_DOWN:手指剛接觸屏幕。 ACTION_MOVE:手指在屏幕上移動。 ACTION_UP:手指從屏幕上松開的一瞬間。下面內容摘自《Android 開發藝術探索》140頁的3.4 View的事件分發機制 內容,所謂點擊事件的事件分發,就是對MotionEvent事件的分發過程,當MotionEvent事件產生之後,系統需要把這個事件傳遞給一個具體的View,其實這個傳遞的過程就是事件的一個分發過程。點擊事件的分發過程由三個很重要的方法來共同完成:dispatchTouchEvent、onInterceptTouchEvent和onTouchEvent。
dispatchTouchEvent(MotionEvent ev):用來進行事件的分發。如果事件能夠傳遞給當前的View,那麼此方法一定會被調用,返回結果受當前View的OnTouchEvent和下級View的dispatchTouchEvent方法的影響,表示是否消耗(處理)當前事件 onInterceptTouchEvent(MotionEvent ev):在上述方法內部調用,用來判斷是否攔截某個事件,如果當前View攔截了某個事件,那麼在同一個事件序列當中,此方法不會再次調用,返回結果表示是否攔截當前事件onTouchEvent(MotionEvent ev):在dispatchTouchEvent方法中調用,用來處理點擊事件,返回結果表示是否消耗當前事件,如果不消耗,則在同一個事件序列中,當前View無法再次收到事件。
上述三個方法的關系可以用下面的偽代碼進行表示:
public boolean dispatchTouchEvent(MotionEvent event){ boolean consume = false; if(onInterceptTouchEvent(event)){ consume = onTouchEvent(event); }else{ consume = child.dispatchTouchEvent(event); return consume; }
上面的偽代碼將三者的關系表現的淋漓極致,一個點擊事件的傳遞規則大致如下:
1. 對於一個點擊事件的根ViewGroup來說,點擊事件產生後,首先會傳給它,這時它的dispatchTouchEvent就會被調用。
2. 如果這個ViewGroup的onInterceptTouchEvent方法返回true就表示要攔截當前事件,接著事件就會交給ViewGroup處理,即它的onTouchEvent方法就會被調用。
3. 如果這個ViewGroup的onInterceptTouchEvent方法返回false就表示它不攔截當前事件,這時當前事件就會繼續傳遞給它的子元素,接著子元素的dispatchTouchEvent就會被調用,如此反復直到事件被最終處理。
當一個點擊事件產生後,它的實際傳遞過程遵循如下順序:
Activity- ->Window- ->View,事件總是最先傳遞給Activity,Activity再傳遞給Window,最後Window再傳遞給頂級View。
事件分發的源碼解析:
點擊事件用MotionEvent表示,當一個點擊操作發生時,事件最先傳遞給當前的Activity,由Activity的dispatchTouchEvent來進行事件派發,具體的工作是由Activity的內部Window來完成的,那我們先從Activity的dispatchTouchEvent來開始分析
public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { onUserInteraction(); } if (getWindow().superDispatchTouchEvent(ev)) { return true; } return onTouchEvent(ev); }
進去瞧瞧onUserInteraction()方法,原來是一個空方法
/** * Called whenever a key, touch, or trackball event is dispatched to the activity.Implement this method if you wish to know that the user has * interacted with the device in some way while your activity is running. * …… * / public void onUserInteraction() {}
讓我們再瞧瞧superDispatchTouchEvent()方法。
* Used by custom windows, such as Dialog, to pass the touch screen event * further down the view hierarchy. Application developers should not need to implement or call this. */ public abstract boolean superDispatchTouchEvent(MotionEvent event);
在Android View的事件分發機制(一)中我們知道PhoneWindow是Window的唯一實現類,猜測PhoneWindow也會將事件直接傳遞給DecorView去實現。看看PhoneWindow中是如何實現這個方法的:
@Override public boolean superDispatchTouchEvent(MotionEvent event) { return mDecor.superDispatchTouchEvent(event); }
果然不出我們所料,會在DecorView中去調用superDispatchTouchEvent這個方法,DecorView又將這個方法的實現交由他的父類ViewGroup去處理,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 accessiiblity 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 ArrayListpreorderedList = buildOrderedChildList(); final boolean customOrder = preorderedList == null && isChildrenDrawingOrderEnabled(); final View[] children = mChildren; for (int i = childrenCount - 1; i >= 0; i--) { final int childIndex = customOrder ? getChildDrawingOrder(childrenCount, i) : i; final View child = (preorderedList == null) ? children[childIndex] : preorderedList.get(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; }
這個方法比較長,這裡還是做分段說明,先看下面一段,很顯然,他描述的是當前View是否攔截點擊事件的處理過程:
// 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); // restore action in case it was changed ev.setAction(action); } 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在如下兩種情況下回判斷是否要攔截當前事件:事件類型為ACTION_DOWN或者mFirstTouchTarget != null。ACTION_DOWN事件好理解,那麼mFirstTouchTarget != null是什麼東東呢?這個從後面的代碼邏輯可以看出來:
1. 當事件由ViewGroup的子元素成功處理是,mFirstTouchTarget 會被賦值並指向子元素。換句話說:當ViewGroup不攔截事件並將事件交由子元素處理時mFirstTouchTarget != null,發過來,一旦事件有當前ViewGroup攔截時mFirstTouchTarget != null就不成立。當ACTION_MOVE和ACTION_UP事件到來時,由於(actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null)這個條件為false,將會導致ViewGroup的onInterceptTouchEvent()不會再被調用,並且同一序列中的其他事件都會默認交給它處理。
2. 當然,這裡有一種特殊情況,那就是FLAG_DISALLOW_INTERCEPT標記位,它的作用就是讓ViewGroup不再攔截事件,當前前提是ViewGroup不攔截ACTION_DOWN 事件。
接著再看當ViewGroup不攔截事件的時候,事件會向下分發交由它的子View進行處理,這段源碼如下:
final View[] children = mChildren; for (int i = childrenCount - 1; i >= 0; i--) { final int childIndex = customOrder ? getChildDrawingOrder(childrenCount, i) : i; final View child = (preorderedList == null) ? children[childIndex] : preorderedList.get(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; } }
上面這段代碼邏輯也很清晰,首先遍歷ViewGroup中的所有子元素,然後判斷子元素是否能夠接收到點擊事件。是否能夠接收點擊事件由兩點來衡量:子元素是否在播動畫和點擊事件的坐標是否落在子元素的區域內。如果某個子元素滿足這兩個條件,那麼事件就會傳遞給它處理。
可以看到,dispatchTransformedTouchEvent()實際上調用的就是子元素的dispatchTouchEvent方法,在它的內部有如下一段內容,而在上面的代碼中child傳遞不是null,因此它會直接調用子元素的dispatchTouchEvent方法,這樣事件就交由子元素處理了。
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; } // Calculate the number of pointers to deliver. final int oldPointerIdBits = event.getPointerIdBits(); final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits; // If for some reason we ended up in an inconsistent state where it looks like we // might produce a motion event with no pointers in it, then drop the event. if (newPointerIdBits == 0) { return false; } // If the number of pointers is the same and we don't need to perform any fancy // irreversible transformations, then we can reuse the motion event for this // dispatch as long as we are careful to revert any changes we make. // Otherwise we need to make a copy. final MotionEvent transformedEvent; if (newPointerIdBits == oldPointerIdBits) { if (child == null || child.hasIdentityMatrix()) { if (child == null) { handled = super.dispatchTouchEvent(event); } else { final float offsetX = mScrollX - child.mLeft; final float offsetY = mScrollY - child.mTop; event.offsetLocation(offsetX, offsetY); handled = child.dispatchTouchEvent(event); event.offsetLocation(-offsetX, -offsetY); } return handled; } transformedEvent = MotionEvent.obtain(event); } else { transformedEvent = event.split(newPointerIdBits); } // 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; }
這個看的腦袋都有點暈了,如果你看到這裡了的話。暫時就分析到這吧。
我們來講一下自定義組合控件,相信大家也接觸過自定義組合控件吧,話不多說,直接干(哈~哈~):大家看到這個覺得這不是很簡單的嗎,這不就是寫個布局文件就搞定嘛,沒錯,確實直接
1 背景 很久沒有更新博客了,忙裡偷閒產出一篇。寫這片文章主要是去年項目中的一個需求,當時三下五除二的將其實現了,但是源碼的閱讀卻一直扔在那遲遲沒有時間理會,
本文的代碼接著上一篇獲取聯系人信息寫的。在獲取聯系人信息的時候,我發現遍歷Cursor來獲取所有聯系人的信息比較慢,比如我手機上有大約不到四百人的聯系方式,全部遍歷一次大
上周android推出了Android Support Library 23.2版本,提供了一些新的API支持和對現有庫增加新特性。先來看看Bottom Sheet這個控