Android的事件分發(fā)機制是一個很重要的知識點省店,也是基礎(chǔ)知識里相對比較難的一個知識點久免,但是其用途還是很廣泛的邪码,比如是复,在自定義view里或者解決滑動嵌套(其實google官方是不支持滑動嵌套的方式的删顶,但是實際項目中還是有很多這種**的設(shè)計的)的時候。
理解事件分發(fā)的機制首先要理解三個方法:
- boolean dispatchTouchEvent (MotionEvent ev)
官方文檔上解釋很簡單就就一句話淑廊,分發(fā)事件到目標視圖逗余,返回結(jié)果是boolean類型的,表示是否消耗該事件季惩,返回true表示事件會被處理录粱,否則相反腻格。其結(jié)果受當前view的onTouchEvent和下級view的dispatchTouchEvent的影響。
- boolean onInterceptTouchEvent (MotionEvent ev)
官網(wǎng)說的很清楚了啥繁,實現(xiàn)這個方法是為了攔截屏幕的觸摸事件荒叶,其實這個方法是在dispatchTouchEvent內(nèi)部調(diào)用的。當需要在onTouchEvent里實現(xiàn)相對復(fù)雜的交互時可以使用這個方法输虱。dispatchTouchEvent返回true的話,表示一整個事件系列都只能交給這個view來處理了脂凶,而且dispatchTouchEvent不會也沒有必要再調(diào)用了宪睹。一旦這個view開始處理事件了,那么它必須消耗掉down事件蚕钦,也就是說onTouchEvent必須返回true亭病,否則的話這一事件序列的其它剩余事件就不會接受到了,事件會重新交給父元素去處理嘶居。類似與如果上級交給你一件事罪帖,你沒有做好,那么同類的事上級短期內(nèi)是不會再交給你的邮屁。
- boolean onTouchEvent (MotionEvent ev)
這個方法官網(wǎng)描述也比較簡單整袁,主要是處理觸摸事件,分發(fā)onClickListener回調(diào)方法佑吝。需要注意的是坐昙,如果這個方法返回true表示這個事件被消耗掉了,否則這個事件不會再接受到同序列的其它事件芋忿,并且事件最終會回到上級去處理炸客。另外,還需要注意的一點是在view中戈钢,onTouchListener的優(yōu)先級要比onTouchEvent要高痹仙,而OnClickListener的優(yōu)先級確實最低的,處于事件傳遞的末尾殉了。如果view中設(shè)置了onTouchListener开仰,事件的處理還得看onTouchListener的回調(diào)函數(shù)onTouch的返回值了,返回值是false的話onTouchEvent就被調(diào)用宣渗,否則不會調(diào)用抖所。
至于這三者的關(guān)系其實網(wǎng)上的到處都有說,但是我覺得最簡潔明了的還是一段偽代碼:
public boolean dispatchTouchEvent(MotionEvent ev){
boolean consume = false;
if (onInterceptTouchEvent(ev)){
consume = onTouchEvent(ev);
}else {
consume = child.dispatchTouchEvent(ev);
}
return consume;
}
當點擊事件產(chǎn)生后痕囱,首先會調(diào)用dispatchTouchEvent田轧,如果onInterceptTouchEvent返回true表示他要攔截事件,接著onTouchEvent就會被調(diào)用鞍恢。如果onInterceptTouchEvent返回false 傻粘,那么表示當前view不會攔截事件每窖,那么這個事件就會繼續(xù)傳遞到子view,于是弦悉,子view的dispatchTouchEvent方法調(diào)用窒典,一直反復(fù)直到事件被處理。
接下來稽莉,看看源碼中的事件處理吧:
點擊事件發(fā)生時瀑志,首先傳遞到activity,然后acitivty在分發(fā)污秆。
/**
* Called to process touch screen events. You can override this to
* intercept all touch screen events before they are dispatched to the
* window. Be sure to call this implementation for touch screen events
* that should be handled normally.
*
* @param ev The touch screen event.
*
* @return boolean Return true if this event was consumed.
*/
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
activty把事件交給了Window來分發(fā)劈猪,如果返回true則事件到此為止了,否則就是此事件子view都沒有處理良拼,又交給activty的onTouchEvent來處理了战得。
我們再看Window的唯一的實現(xiàn)類PhoneWindow的事件分發(fā)方法。
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}```
可以看到事件繼續(xù)交給了頂層View DecorView了庸推,頂層布局一般都是ViewGroup常侦,DecorView也不例外,其實它的實現(xiàn)類是繼承于FrameLayout的贬媒。我們按住shift鍵繼續(xù)往里點擊聋亡。可以看到ViewGroup里的dispatchTouchEvent方法掖蛤。
源碼太長了杀捻,這里只貼出一部分,在2206~2221行的這一段代碼里主要是判斷事件是否會被攔截蚓庭。
// 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;
}
由上面可以看出只有在down事件和mFirstTouchTarget != null時才需要判斷致讥,否則事件都是要攔截的。mFirstTouchTarget是"接受觸摸事件的View"所組成的單鏈表器赞,一旦ViewGroup子元素成功處理事件時mFirstTouchTarget就會被賦值垢袱。也就是說,只要當前ViewGroup不攔截事件那么 mFirstTouchTarget就不會為空港柜。
當Viewgroup不攔截事件時请契,事件將會交給它的子view來處理
// 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;
}
遍歷子元素,如果事件的坐標是在子元素的區(qū)域內(nèi)或者子元素在播放動畫夏醉,那么子元素就能夠接受收事件
跟進dispatchTransformedTouchEvent方法:
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;
}
child不是null時爽锥,事件就交給子 view的dispatchTouchEvent來處理了。現(xiàn)在我們來看看view 的dispatchTouchEvent源碼:
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;```
view 無需再向下傳遞事件了畔柔,所以只能自己處理了氯夷。源碼中,首先會判斷OnTouchListener是否為null靶擦。如果onTouch方法返回true腮考,那么onTouchEvent方法便不會調(diào)用雇毫。因此可見OnTouchListener的優(yōu)先級還是高于onTouchEvent的。
看源碼很累啊踩蔚。棚放。。馅闽。飘蚯。。
分析參考《Android開發(fā)藝術(shù)探索》