10分鐘瞭解Android的事件分發
什麼是事件分發?
大家知道Android中的視圖是由一個個View嵌套構成的層級視圖,即一個View裏包含有子View,而這個子View裡面又可以再添加View。當用戶觸摸屏幕產生一系列事件時,事件會由高到低,由外向內依次傳遞,最終把事件交到一個具體的View手上處理,這個傳遞的過程就叫做事件分發。
從手觸摸屏幕開始所產生一系列MotionEvent事件,將事件傳遞到具體的某一個View的過程就叫做事件分發。
Android將觸摸事件統一封裝成MontionEvent類,以Down事件開始,Up事件結束,中間可能會產生其實事件(例如Move),組成一個完整的事件系列。
同時事件分發又有三個重要的方法:
boolean dispatchTouchEvent(MotionEvent e)
如果事件能夠傳遞給當前View,此方法一定會被調用,意味著當前View接受到事件。
boolean onInterceptTouchEvent()
在dispatchTouchEvent方法中調用,用來判斷是否要攔截當前事件。基本上不攔截事件。
boolean onTouchEvent()
在dispatchTouchEvent方法中調用,用來處理點擊事件。返回ture則意味事件被消費。
三大方法有著千絲萬縷的關係。調用dispatchTouchEvent()方法則說明事件已經交到該View手上了,接來下要麼View自己攔截(onInterceptTouchEvent())處理事件,要麼傳遞給子View。
public boolean dispatchTouchEvent(MotionEvent ev){
boolean consume;
if(onInterceptTouchEvent(ev)){
consume = onTouchEvent(ev);
}else {
consume = child.dispatchTouchEvent(ev);
}
return consume;
}
舉個例子:
小明的父親準備將傳家寶傳給小明(dispatchTouchEvent)。小明拿到傳家寶後,立馬對自己的兒子進行了重重考覈(onInterceptTouchEvent),最終小明覺得自己的兒子太不爭氣了。就決定不把傳家寶交給兒子,把寶貝拿去賣了換錢養老(onTouchEvent)。所以到這,該寶貝傳到小明手上就斷了傳承,同理事件也就意味著結束了。當然如果小明兒子挺爭氣的,小明就會把傳家寶傳給兒子。到了小明的兒子手上又如此向下反覆傳承。直至有後代自己把寶貝處理了,斷了傳承,事件也才被消費結束。
小明有後代的情況下才有義務把傳家寶傳下去,所以他會把傳家寶傳給符合自己要求的兒子,如果兒子不符合要求,則自己拿來養老。所以ViewGroup的dispatchTouchEvent()一般都不攔截事件,只有在很苛刻的條件下才會主動攔截。接下來再找到符合條件的子View,把事件傳遞給他。
如果小明終無後人,則傳家寶到小明手上後就斷了傳承,自己連傳和不傳的選擇都沒有,只能自己想辦法給處理了。所以View沒有onInterceptTouchEvent()方法,交到View手上也就意味著事件即將處理。(此View非彼View,例如TextView這種單獨的View,不能再添加子View)
從那兒開始發事件?
事件最終會交給一個View處理,那事件最開始是從那兒傳遞的呢?Activity。
產生事件最先會交給Activity,再依次向下傳遞。Activity
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//空實現
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
PhoneWindow
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
DecorView
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
Activity會將事件傳遞給Window,window又會向下繼續傳遞。如果最終都沒有View消費事件(superDispatchTouchEvent返回false),則Activity會自己調用onTouchEvent()方法處理事件。
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
而PhoneWindow又會把事件傳遞給DecorView(FrameLayout)。這篇文章對三者之間的關係有一個簡單的說明。而FrameLayout(包括其他4大布局)都沒有重寫dispatchTouchEvent()方法,所以系統的事件傳遞規則都會按照ViewGroup的dispatchTouchEvent()方法處理。
graph TB
A{Activity}-->B{Window}
B{Window}-->C{DecorView}
從小明有兒子的情況說起
// 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);
} else {
intercepted = false;
}
} else {
intercepted = true;
}
ViewGroup的dispatchTouchEvent()方法會先判斷自己是否要攔截當前事件,是否攔截的作用在於,是自己處理事件,還是要將事件傳遞下去。即intercepted為true自己處理,為false則尋找子View向下傳遞。當然如果沒有符合傳遞要求的子View,事件還是會由當前View自己處理。
if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null)
actionMasked == MotionEvent.ACTION_DOWN好理解。其二,當子View消費事件時,父View會把消費事件的子View用鏈表記錄下來,方便後續事件傳遞,而mFirstTouchTarget就是鏈表表頭。沒有子View能夠接受事件,或者子View接受到事件但是不消費,mFirstTouchTargets為null。就會造成下次產生其它事件,走到這裡該表達式沒有一個為真,則當前View直接攔截事件處理。以後的事件子View想都不要想了。
如果View開始處理事件,但是不消耗最開頭的ACTION_DONW事件(例如:執行onTouchEvent()方法卻返回false),以後同系列的事件都不會再交給他。
同時父View以後也不會再有機會執行onInterceptTouchEvent()方法。final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
該表達式默認情況下為false,所以會調用onInterceptTouchEvent()方法,但onInterceptTouchEvent()還是不攔截返回false。我們可以調用requestDisallowInterceptTouchEvent(boolean disallowIntercept)方法修改標誌位mGroupFlags,即(mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0表達式成立為ture。
但intercepted還是為false不攔截?那這個表達式和requestDisallowInterceptTouchEvent()方法的價值和意義在哪兒??
如我們表面所看到的,目的就是為了執不執行onInterceptTouchEvent()方法。例如:當我們自定義View時,在InterceptTouchEvent()方法中處理事件攔不攔截的邏輯。子View可以調用parent.requestDisallowInterceptTouchEvent(true)方法可以讓父View沒機會執行處理攔截的邏輯,直接讓父View開始傳遞事件。就像小明兒子不管父親對自己有什麼樣的看法,直接把傳家寶搶到自己手上一個道理。
事件為Down時會重置mGroupFlags標誌位狀態,即無論怎樣還是要走一遭onInterceptTouchEvent()方法。
// 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);
//重置mGroupFlags
resetTouchState();
}
走到這後,如果intercept為false,則小明心裏面已經沒有自己賣掉傳家寶的想法了。此時是想把傳家寶傳下去的,接下來就是挑選合格的繼承人了。
遍歷子View,將事件傳遞給符合條件的View。
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
//i
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
//children[i]
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;
}
/*
*canViewReceivePointerEvents()確保子View要可見。執行補間動畫時View會變成可見,即使View的Visibility屬性為INVISIBLE。
*isTransformedTouchPointInView()判斷事件的坐標是否落在當前子View的區域內。
*/
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
//如果之前已有事件交由子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
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
mLastTouchDownTime = ev.getDownTime();
//反射測試preorderedList == null,該集合按照子View繪製順序和Z軸排序子View。
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
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
// The accessibility focus didnt handle the event, so clear
// the flag and do a normal dispatch to all children.
ev.setTargetAccessibilityFocus(false);
}
ViewGroup,挑選傳遞事件的子View要符合兩個條件:
可見狀態
事件的坐標在子View範圍
符合這兩個條件,則調用dispatchTransformedTouchEvent()方法把事件傳遞給子View。dispatchTransformedTouchEvent()方法會根據child參數來做不同的處理,當子View為null時調用View的dispatchTouchEvent()傳遞事件,意味當前View自己處理事件。child不為null的情況下,則調用child的dispatchTouchEvent()把事件交給子View。
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);
}