<h1 align = "center">Android事件分發(fā)機制</h1>
前言:網(wǎng)上有很多關(guān)于Android事件分發(fā)的文章默伍,但大多是基于使用經(jīng)驗或者Log來總結(jié)出來的,本文主要從源碼進(jìn)行分析衰琐,徹底了解Android事件分發(fā)的原理也糊。以下的內(nèi)容都是基于Android7.1源碼的。
Activity的事件分發(fā)機制
一般情況下碘耳,對于應(yīng)用層來說显设,事件的分發(fā)是從Activity接收到來自系統(tǒng)的TouchEvent開始的。Activity的dispatchTouchEvent首先被調(diào)用:
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
// 可以重寫這個方法辛辨,處理ACTION_DOWN事件捕捂,可以看出瑟枫,任何事件序列都會首先調(diào)用這個函數(shù),如果需要監(jiān)聽用戶是否觸摸屏幕指攒,那么建議重寫這個函數(shù)即可慷妙。
onUserInteraction();
}
// 將事件交由Window處理,返回true表示事件已經(jīng)消耗掉了允悦,于是返回true告訴系統(tǒng)膝擂。
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
// 如果該事件沒有被Window消耗掉,那么Activity的TouchEvent將會被調(diào)用隙弛。
return onTouchEvent(ev);
}
Activity的事件分發(fā)比較簡單架馋,由源碼可以看出,如果Window消耗了事件全闷,或者Activity自身的onTouchEvent消耗了事件叉寂,都將會返回true,告訴系統(tǒng)事件已經(jīng)被消耗掉。
我們知道总珠,一個事件序列基本都是由ACTION_DOWN,ACTION_MOVE...,ACTION_MOVE,ACTION_UP構(gòu)成的屏鳍,在Activity的事件分發(fā)機制里面,一個事件序列里面的每個子事件的處理都是獨立開來的局服,即钓瞭,就算Activity不消耗ACTION_DOWN事件,接下來的ACTION_MOVE,ACTION_UP等事件都會繼續(xù)傳遞給Activity處理淫奔。
Window的事件分發(fā)機制
在事件分發(fā)的過程中山涡,Window只是作為中間的橋梁,這里沒什么好說的搏讶。直接源碼:
// 這個函數(shù)是在PhoneWindow里面的佳鳖,實際上Activity中的Window,就是一個PhoneWindow
public boolean superDispatchTouchEvent(MotionEvent event) {
// 直接交由DecorView處理
return mDecor.superDispatchTouchEvent(event);
}
ViewGroup的事件分發(fā)機制
查看DecorView的源碼發(fā)現(xiàn)霍殴,實際上媒惕,就是間接調(diào)用ViewGroup的dispatchTouchEvent,因為DecorView繼承自FrameLayout来庭,F(xiàn)rameLayout繼承自ViewGroup妒蔚,F(xiàn)rameLayout并沒有重寫dispatchTouchEvent函數(shù),所以最終調(diào)用的是ViewGroup的dispatchTouchEvent月弛。
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
下面是把一些無關(guān)的代碼刪除后肴盏,ViewGroup的dispatchTouchEvent的實現(xiàn),每一事件序列都維護(hù)著一個觸摸鏈表帽衙,觸摸鏈表的節(jié)點實體是TouchTarget菜皂,
事件序列中的任一事件,將會更新觸摸鏈表厉萝。觸摸鏈表是當(dāng)前觸點可以觸摸到的子View的集合恍飘,例如一個ViewGroup中有2個子View榨崩,A和B,A和B有重合的部分章母,
如果手指觸摸到重合的部分母蛛,那么觸摸鏈表里面就是A和B,如果只是觸摸到A獨有的部分乳怎,那么觸摸鏈表就是只有A彩郊。
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean handled = false;
// 過濾一些不安全的觸摸事件,比如當(dāng)前View被別的可見分Window遮擋住了蚪缀。
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
if (actionMasked == MotionEvent.ACTION_DOWN) {
// 清除之前的事件序列狀態(tài)秫逝,另外,如果上一個事件序列結(jié)束后询枚,當(dāng)前這個ViewGroup被設(shè)置成不攔截事件的筷登,
// 那么在這個事件開始時,總是被設(shè)置成可以攔截事件哩盲。即設(shè)置FLAG_DISALLOW_INTERCEPT只是在一個事件序列內(nèi)有效前方。
// mFirstTouchTarget也會被清除。
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// Check for interception.
final boolean intercepted;
// 一般情況下廉油,如果是ACTION_DOWN事件惠险,那么mFirstTouchTarget就為null,因為在上面的代碼里面抒线,ACTION_DOWN事件將會首先清除觸摸鏈表
// 如果不是ACTION_DOWN班巩,而這個時候mFirstTouchTarget不為null,那么說明嘶炭,ACTION_DOWN事件已經(jīng)被當(dāng)前ViewGroup的某一個子View消耗了
// 于是會繼續(xù)嘗試攔截抱慌,于是可以得出:ViewGroup可以在事件序列的任一個節(jié)點阻止事件繼續(xù)往下傳遞。
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
// 是否允許攔截事件眨猎,記住抑进,F(xiàn)LAG_DISALLOW_INTERCEPT會在ACTION_DOWN事件到來時被重設(shè),所以睡陪,
// onInterceptTouchEvent 總是會被調(diào)用(ACTION_DOWN事件)
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
// 我們可以重寫ViewGroup的onInterceptTouchEvent來決定要不要攔截事件
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// 如果不是ACTION_DOWN寺渗,而這個時候mFirstTouchTarget又為null,那么說明ACTION_DOWN事件已經(jīng)被當(dāng)前的ViewGroup攔截了兰迫,或者是
// 沒有子View消耗ACTION_DOWN事件信殊,
// 于是,當(dāng)前ViewGroup應(yīng)該繼續(xù)攔截接下來的一個事件序列內(nèi)的所有事件汁果。
intercepted = true;
}
// 如果事件被攔截了涡拘,或者有子View處理了,都進(jìn)行正常的分發(fā)据德。
if (intercepted || mFirstTouchTarget != null) {
ev.setTargetAccessibilityFocus(false);
}
// 檢查該事件是否應(yīng)該取消鳄乏。
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 ArrayList<View> preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
// 遍歷所有子View,并將事件分發(fā)給子View(如果該子View能接受事件的話)汞窗。
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如果不可見姓赤,或者事件坐標(biāo)不在View范圍內(nèi),那么View不能處理該事件仲吏。
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
// 執(zhí)行到這里的時候不铆,說明View是具有響應(yīng)當(dāng)前事件的能力的(看上面的if語句)
// 假設(shè)當(dāng)前事件不是DOWN事件,那么View應(yīng)該就在觸摸鏈表中了裹唆,即newTouchTarget不為null誓斥,
// 于是將會跳出循環(huán)
// 例外的情況是:如果是滑動的時候,滑到了一個全新的子View中许帐,newTouchTarget == null,那么就會跑下面的代碼
// 將該子View加入到觸摸鏈表中劳坑。
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);
// 將事件傳遞給子View,子View的dispatchTouchEvent被調(diào)用
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();
// 這個子view不再觸摸鏈表中成畦,但是其能夠響應(yīng)當(dāng)前的事件距芬,所以理應(yīng)將它加入到觸摸鏈表中。
// 將該子View插入到觸摸目標(biāo)的鏈表頭部循帐。
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();
}
// 如果沒有找到消耗當(dāng)前事件的子View框仔,那么最新的觸摸目標(biāo)指向最遲最近的的觸摸目標(biāo)
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) {
// mFirstTouchTarget == null 說明觸摸鏈表是空的,表示ViewGroup中沒有子View響應(yīng)該事件拄养,那么
// ViewGroup被當(dāng)做是View對待离斩,即ViewGroup的父類的dispatchTouchEvent被調(diào)用。ViewGroup的父類是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;
// 遍歷觸摸鏈表跛梗,一個一個分發(fā)給鏈表中的view。
while (target != null) {
final TouchTarget next = target.next;
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
// 如果分發(fā)過了棋弥,那么就不再重復(fù)分發(fā)了
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
// 分發(fā)給鏈表中的view
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
// 因為觸摸點是不停變化的核偿,那么觸摸鏈表也在不停變化,
// 對于一些不再能夠響應(yīng)事件的鏈表節(jié)點嘁锯,將它從鏈表中移除宪祥。
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的事件分發(fā)機制
View的事件分發(fā)比較簡單聂薪,如果有設(shè)置onTouchListener家乘,那么onTouchListener首先響應(yīng)事件,
onTouchListener 如果不消耗事件藏澳,那么輪到onTouchEvent響應(yīng)事件仁锯,如果連onTouchEvent都不消耗事件,
那么表明該View不消耗事件翔悠,返回false业崖,將事件交由父View處理野芒。
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();
}
// 如果當(dāng)前View被別的可見的Window遮擋,那么無法響應(yīng)事件
// 例如Toast
if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
// 如果View有設(shè)置OnTouchListener双炕,那么OnTouchListener首先響應(yīng)事件狞悲。
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
// 如果OnTouchListener不響應(yīng)事件,那么輪到onTouchEvent響應(yīng)事件
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;
}