參考http://www.gcssloop.com/customview/dispatch-touchevent-source這篇文章并增加了一些我的理解的注釋。(呃,View部分比較簡(jiǎn)單好理解,所以我主要是在ViewGroup 上增加了一些一開(kāi)始懵逼的地方的注釋?zhuān)?br>
事件分發(fā)源碼先講View的,再講ViewGroup 的。
1、View
View 事件相關(guān)的各個(gè)方法調(diào)用順序(都是在dispatchTouchEvent方法中的,因?yàn)閐ispatchTouchEvent就是用來(lái)處理事件分發(fā)的):
onTouchListener > onTouchEvent > onLongClickListener > onClickListener
public boolean dispatchTouchEvent(MotionEvent event) {
...
boolean result = false; // result 為返回值,主要作用是告訴調(diào)用者事件是否已經(jīng)被消費(fèi)。
if (onFilterTouchEventForSecurity(event)) {
ListenerInfo li = mListenerInfo;
/**
* 如果設(shè)置了OnTouchListener,并且當(dāng)前 View 可點(diǎn)擊,就調(diào)用監(jiān)聽(tīng)器的 onTouch 方法,
* 如果 onTouch 方法返回值為 true,就設(shè)置 result 為 true。
*/
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
/**
* 如果 result 為 false,則調(diào)用自身的 onTouchEvent。
* 如果 onTouchEvent 返回值為 true,則設(shè)置 result 為 true。
*/
if (!result && onTouchEvent(event)) {
result = true;
}
}
...
return result;
}
用偽代碼實(shí)現(xiàn)應(yīng)當(dāng)是這樣的
public boolean dispatchTouchEvent(MotionEvent event) {
if (mOnTouchListener.onTouch(this, event)) {
return true;
} else if (onTouchEvent(event)) {
return true;
}
return false;
}
OnClick 和 OnLongClick 的具體調(diào)用位置在 onTouchEvent 中,看源碼(同樣省略大量無(wú)關(guān)代碼):
public boolean onTouchEvent(MotionEvent event) {
...
final int action = event.getAction();
// 檢查各種 clickable
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
(viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
switch (action) {
case MotionEvent.ACTION_UP:
...
removeLongPressCallback(); // 移除長(zhǎng)按
...
performClick(); // 檢查單擊
...
break;
case MotionEvent.ACTION_DOWN:
...
checkForLongClick(0); // 檢測(cè)長(zhǎng)按
...
break;
...
}
return true; // ??表示事件被消費(fèi)
}
return false;
}
注意上面代碼中存在一個(gè) return true; 并且是只要 View 可點(diǎn)擊就返回 true,就表示事件被消費(fèi)了。
2、ViewGroup
1.判斷自身是否需要(詢問(wèn) onInterceptTouchEvent 是否攔截),如果需要,調(diào)用自己的 onTouchEvent。
2.自身不需要或者不確定,則詢問(wèn) ChildView ,一般來(lái)說(shuō)是調(diào)用手指觸摸位置的 ChildView。
3.如果子 ChildView 不需要?jiǎng)t調(diào)用自身的 onTouchEvent。
用偽代碼應(yīng)該是這樣的:
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean result = false; // 默認(rèn)狀態(tài)為沒(méi)有消費(fèi)過(guò)
if (!onInterceptTouchEvent(ev)) { // 如果沒(méi)有攔截交給子View
result = child.dispatchTouchEvent(ev);
}
if (!result) { // 如果事件沒(méi)有被消費(fèi),詢問(wèn)自身onTouchEvent
result = onTouchEvent(ev);
}
return result;
}
實(shí)際源碼:
public boolean dispatchTouchEvent(MotionEvent ev) {
// 調(diào)試用
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
// 判斷事件是否是針對(duì)可訪問(wèn)的焦點(diǎn)視圖(很晚才添加的內(nèi)容,個(gè)人猜測(cè)和屏幕輔助相關(guān),方便盲人等使用設(shè)備)
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;
// 處理第一次ACTION_DOWN.
if (actionMasked == MotionEvent.ACTION_DOWN) {
// 清除之前所有的狀態(tài)
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// 檢查是否需要攔截.
final boolean intercepted;
//actionMasked == MotionEvent.ACTION_DOWN這個(gè)條件指的是事件第一次到來(lái)的時(shí)候(肯定是ACTION_DOWN先到?。? //mFirstTouchTarget一開(kāi)始是null,viewgroup的子元素成功處理了事件后,才會(huì)給mFirstTouchTarget賦值。
//mFirstTouchTarget!=null這個(gè)條件在ACTION_DOWN的時(shí)候是null的 因?yàn)槿缟厦嫠f(shuō)只有viewgroup不攔截事件,分發(fā)給子元素并且成功處理了事件后mFirstTouchTarget才!=null。
if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev); // 詢問(wèn)是否攔截
ev.setAction(action); // 恢復(fù)操作,防止被更改
} else {
intercepted = false;
}
} else {
// 沒(méi)有目標(biāo)來(lái)處理該事件,而且也不是一個(gè)新的事件事件(ACTION_DOWN), 進(jìn)行攔截。
intercepted = true;
}
// 判斷事件是否是針對(duì)可訪問(wèn)的焦點(diǎn)視圖
if (intercepted || mFirstTouchTarget != null) {
ev.setTargetAccessibilityFocus(false);
}
// 檢查事件是否被取消(ACTION_CANCEL).
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
// 如果沒(méi)有取消也沒(méi)有被攔截 (進(jìn)入事件分發(fā))
if (!canceled && !intercepted) {
// 如果事件是針對(duì)可訪問(wèn)性焦點(diǎn)視圖,我們將其提供給具有可訪問(wèn)性焦點(diǎn)的視圖。
// 如果它不處理它,我們清除該標(biāo)志并像往常一樣將事件分派給所有的 ChildView。
// 我們檢測(cè)并避免保持這種狀態(tài),因?yàn)檫@些事非常罕見(jiàn)。
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();
final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
: TouchTarget.ALL_POINTER_IDS;
// 清除此指針I(yè)D的早期觸摸目標(biāo),防止不同步。
removePointersFromTouchTargets(idBitsToAssign);
final int childrenCount = mChildrenCount;
if (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex); // 獲取觸摸位置坐標(biāo)
final float y = ev.getY(actionIndex);
// 查找可以接受事件的 ChildView
final ArrayList<View> preorderedList = 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);
// 如果有一個(gè)視圖具有可訪問(wèn)性焦點(diǎn),我們希望它首先獲取事件,
// 如果不處理,我們將執(zhí)行正常的分派。
// 盡管這可能會(huì)分發(fā)兩次,但它能保證在給定的時(shí)間內(nèi)更安全的執(zhí)行。
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
// 檢查View是否允許接受事件(即處于顯示狀態(tài)(VISIBLE)或者正在播放動(dòng)畫(huà))
// 檢查觸摸位置是否在View區(qū)域內(nèi)
//view不符合條件,continue跳出本次循環(huán)
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
//到了這里,說(shuō)明觸摸位置在View區(qū)域內(nèi)
// getTouchTarget 中判斷了 child 是否包含在 mFirstTouchTarget 中
// 如果有返回 target,如果沒(méi)有返回 null
newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
// ChildView 已經(jīng)準(zhǔn)備好接受在其區(qū)域內(nèi)的事件。
newTouchTarget.pointerIdBits |= idBitsToAssign;
break; // ??已經(jīng)找到目標(biāo)View,跳出循環(huán)
}
resetCancelNextUpFlag(child);
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
//dispatchTransformedTouchEvent實(shí)際上調(diào)用的就是子元素的dispatchTouchEvent方法
mLastTouchDownTime = ev.getDownTime();
if (preorderedList != null) {
for (int j = 0; j < childrenCount; j++) {
if (children[childIndex] == mChildren[j]) {
mLastTouchDownIndex = j;
break;
}
}
} else {
mLastTouchDownIndex = childIndex;
}
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
//子元素的dispatchTouchEvent方法返回true的情況下,
//在addTouchTarget 方法內(nèi)部mFirstTouchTarget會(huì)被賦值
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
ev.setTargetAccessibilityFocus(false);
}
if (preorderedList != null) preorderedList.clear();
}
if (newTouchTarget == null && mFirstTouchTarget != null) {
// 沒(méi)有找到 ChildView 接收事件
newTouchTarget = mFirstTouchTarget;
while (newTouchTarget.next != null) {
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}
// 分發(fā) TouchTarget
if (mFirstTouchTarget == null) {
//說(shuō)明子元素的dispatchTouchEvent方法返回false
// 沒(méi)有 TouchTarget,將當(dāng)前 ViewGroup 當(dāng)作普通的 View 處理。
//dispatchTransformedTouchEvent的child參數(shù)為null,在方法內(nèi)部會(huì)調(diào)用super. dispatchTouchEvent(event)。
//因?yàn)閂iewGroup的父類(lèi)是View,所以此處相當(dāng)于調(diào)用View的dispatchTouchEvent。交由第一部分的View的事件分發(fā)機(jī)制來(lái)處理了。。
//比如viewgroup的子類(lèi)inTouchEvent都return false,并且viewgroup設(shè)置點(diǎn)擊事件那么就會(huì)把viewgroup按照view的事件分發(fā)機(jī)制來(lái)處理
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
// 分發(fā)TouchTarget,如果我們已經(jīng)分發(fā)過(guò),則避免分配給新的目標(biāo)。
// 如有必要,取消分發(fā)。
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;
}
}
// 如果需要,更新指針的觸摸目標(biāo)列表或取消。
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;
}