View事件分發(fā)
在Android中,View無處不在,不管是一個(gè)普通的視圖,還是一個(gè)復(fù)雜的布局,都是依靠View來實(shí)現(xiàn)。而View中的事件分發(fā)和處理,是其核心知識(shí)點(diǎn)之一,也是開發(fā)者學(xué)習(xí)View時(shí)的難點(diǎn)。
在分析事件處理前,我們需要明白,android中一個(gè)完整的手勢(gesture)包括如下4個(gè)操作:
- DOWN: 當(dāng)用戶手指按下時(shí)
- MOVE: 當(dāng)用戶開始滑動(dòng)時(shí)
- UP: 用戶抬起手指
- CANCEL: 取消操作,事件被無法到達(dá)時(shí)
任何一個(gè)手勢都需要從DOWN開始。
在事件分發(fā)中,我們需要區(qū)分View和ViewGroup,雖然后者也是繼承與View,但是ViewGroup重寫了dispatchTouchEvent()方法,同時(shí),也只有在ViewGroup會(huì)處理onInterceptTouchEvent()方法,而一個(gè)事件分發(fā)過程,是從一個(gè)ViewGroup開始,在這過程中我們需要了解以下三個(gè)重要的方法:
- dispatchTouchEvent()
- onInterceptTouchEvent()
- onTouchEvent()
其中,dispatchTouchEvent負(fù)責(zé)將事件分發(fā)到其子View或當(dāng)前View中。onInterceptTouchEvent方法僅存在與ViewGroup中,用于攔截點(diǎn)擊事件,優(yōu)先級(jí)高于onTouchEvent。onTouchEvent中完成對點(diǎn)擊事件的處理,可以攔截并消耗事件。三者的關(guān)系可以根據(jù)如下偽代碼來表示:
public boolean dispatchTouchEvent(Motion e){
boolean result=false;
if(onInterceptTouchEvent(e)){
//如果當(dāng)前View截獲事件,那么事件就會(huì)由當(dāng)前View處理,即調(diào)用onTouchEvent()
result=onTouchEvent(e);
}else{
//如果不截獲那么交給其子View來分發(fā)
result=child.dispatchTouchEvent(e);
}
return result;
}
dispatchTouchEvent
dispatchTouchEvent是事件分發(fā)的主入口,即所有的事件處理都是從這里開始的,在View和ViewGroup中有著不同實(shí)現(xiàn)。
View中的實(shí)現(xiàn)
首先是在View中,dispatchTouchEvent將事件分配到對應(yīng)方法中處理手勢事件,可以看以下源碼:
/**
* Pass the touch screen motion event down to the target view, or this
* view if it is the target.
*
* @param event The motion event to be dispatched.
* @return True if the event was handled by the view, false otherwise.
*/
public boolean dispatchTouchEvent(MotionEvent event) {
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)) {
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
//將事件從分配到OnTouchListener接口來處理事件
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
//將事件分配到onTouchEvent來處理事件
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中常用的兩個(gè)方法OnTouchListener和OnClick。在dispatchTouchEvent中,會(huì)首先判斷OnTouchListener是否為空,如果代碼中對View調(diào)用了setOnTouchListener,那么這里會(huì)直接處理,同時(shí)跳過對onTouchEvent(OnClick在該方法中被執(zhí)行)的調(diào)用,否則會(huì)直接執(zhí)行onTouchEvent事件。因此,在View中,OnTouchListener的優(yōu)先級(jí)高于OnClick,同時(shí)一個(gè)手勢操作最多只能被其中一個(gè)處理。大致的關(guān)系可以通過下圖來理解:

ViewGroup中的實(shí)現(xiàn)
與View不同,在ViewGroup中的dispatchTouchEvent,負(fù)責(zé)將事件傳遞到子事件中,而不會(huì)直接對該事件進(jìn)行處理。部分源碼如下:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
……
//非取消狀態(tài)和中斷狀態(tài)
if (!canceled && !intercepted) {
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 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 = buildOrderedChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
//循環(huán)子View,傳遞手勢事件。
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 (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
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);
//分發(fā)到子View中
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;
}
}
if (preorderedList != null) preorderedList.clear();
}
……
}
}
……
}
該方法中會(huì)調(diào)用dispatchTransformedTouchEvent方法:
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
……
// 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);
}
……
}
可以看出最終還是會(huì)執(zhí)行到View中的dispatchTouchEvent。
onTouchEvent
該方法在View中實(shí)現(xiàn),當(dāng)然你也可以在子類中重寫該方法。為了更好的理解onTouchEvent中對手勢的處理規(guī)則。我們需要借助如下圖:

圖中A為根布局容器,B是依賴于A的子布局容器,C是B中的子View,三者的位置關(guān)系是A->B->C。
關(guān)于處理規(guī)則需要注意兩點(diǎn):
多個(gè)View間的onTouchEvent執(zhí)行順序
當(dāng)在ViewGroup中存在多個(gè)View或ViewGroup疊加顯示時(shí),gesture事件將會(huì)以自上而下的順序來執(zhí)行,即最靠近屏幕的C先執(zhí)行onTouchEvent方法,然后依次向下傳遞。即C->B->A返回Ture還是False:
onTouchEvent是帶boolean型的返回參數(shù),其返回值的意義在于是否消耗并處理該事件。在一個(gè)完整的gesture事件序列中,手勢會(huì)從DOWN事件開始,如果在onTouchEvent中返回的true,那么該gesture的余下手勢事件都會(huì)被該View處理消耗,不再向下傳遞相關(guān)事件。而當(dāng)onTouchEvent在DOWN事件中返回了false,即表示不關(guān)心該gesture事件序列,那么該View將不會(huì)接收到剩余的其它手勢事件,并將其傳遞給下一個(gè)View進(jìn)行處理。官方文檔中給出的說明如下:
True if the event was handled, false otherwise.
onInterceptTouchEvent
上面說到onTouchEvent是至上而下傳遞的,靠近屏幕的View擁有處理手勢事件的高優(yōu)先級(jí),那么有沒有方法改變這種優(yōu)先級(jí)順序呢?比如圖上B和C同時(shí)在DOWN事件中返回了ture,如何將事件分配給B而不是在最頂層的C。ViewGroup中提供了onInterceptTouchEvent方法,通過該方法,我們可以在onTouchEvent方法被調(diào)用之前去攔截該手勢事件,攔截后的事件會(huì)被分配到該View下的onTouchEvent方法中去處理。與onTouchEvent相反,該方法的手勢事件傳遞過程是自下而上,也就是從根View開始傳遞到上層的子View。同時(shí)在gesture事件序列中,所有的手勢事件都可以通過onInterceptTouchEvent方法被攔截,這樣對于手勢的處理有更大的自由度,而不是像onTouchEvent一樣局限在DOWN事件下。
通過onTouchEvent和onInterceptTouchEvent結(jié)合使用,手勢事件實(shí)現(xiàn)了先上后下的一個(gè)過程,我們可以通過特定的方法在某個(gè)點(diǎn)進(jìn)行事件的處理。下面總結(jié)了一張Down事件在上圖中的傳遞過程的圖,該過程中事件不被消耗,完整的被執(zhí)行。
