之前自認為對于Android的事件分發機制還算比較了解,直到前一陣偶然跟人探討該問題,才發現自己以前的理解有誤,慚愧之余遂決定研習源碼,徹底弄明白Android的事件分發機制,好了廢話少說,直接開干。
首先,我們對Android中的touch事件做一下總結,主要分為以下幾類:
1、Action_Down 用戶手指觸碰到屏幕的那一刻,會觸發該事件;
2、Action_Move 在觸碰到屏幕之后,手指開始在屏幕上滑動,會觸發Action_Move事件;
3、Action_Up 在用戶手指從屏幕上離開那一刻開始,會觸發Action_Up事件;
4、Action_Cancel Cancel事件一般跟Up事件的處理是一樣的,是由系統代碼自己去觸發,比如子view的事件被父view給攔截了,之前被分發的子view就會被發送cancel事件,或者用戶手指在滑動過程中移出了邊界。另外,在有多點觸控事件時,還會陸續觸發ACTION_POINTER_DOWN、ACTION_POINTER_UP等事件。
其次,我們知道Android中負責事件分發機制的方法主要有以下三個:
1、dispatchTouchEvent(MotionEvent event) --- 分發事件
我們知道當用戶觸摸到手機屏幕時,最先接收到事件并進行相應處理的應該是最外層的Activity,所以我們來看看Activity中是如何對事件進行分發的。
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
從以上代碼中我們可以看到調用getWindow().superDispatchTouchEvent(),而這里的getWindow()返回的是Window抽象類,其實就是PhoneWindow類,繼承于Window抽象類,然后調用PhoneWindow的superDispatchTouchEvent(),
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
從superDispatchTouchEvent()方法中可以看到,它又調用了mDecor的superDispatchTouchEvent()方法,再看mDecor的superDispatchTouchEvent()方法,
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
而mDecor是何許人也,其實就是PhoneWindow中的一個內部類DecorView的實例對象,是Activity的Window窗口中最根部的父容器,我們平時在Activity的onCreate()方法中,通過setContentView()給設置的布局容器,都屬于mDecor的子View mContentView對象的子view,而DecorView又繼承于FrameLayout,FrameLayout又繼承于ViewGroup,由此可知,Activity是如何將事件分發到相應的View當中去的:
Activity.dispatchTouchEvent(MotionEvent event) -> PhoneWindow.superDispatchTouchEvent(MotionEvent event) -> DecorView.superDispatchTouchEvent(MotionEvent event) -> FrameLayout.dispatchTouchEvent(MotionEvent event) -> ViewGroup.dispatchTouchEvent(MotionEvent event) -> 再逐級分發到各個ViewGroup/View當中去
另外從以上分析過程可以看出,有一點需注意,就是我們在繼承ViewGroup或其子類復寫dispatchTouchEvent時,在方法最后的返回值處,最好別直接寫成return true或者return false,而應寫成super.dispatchTouchEvent,否則無法對事件繼續進行逐級分發,因為在ViewGroup類的dispatchTouchEvent(MotionEvent event)方法中,會對該布局容器內的所有子View進行遍歷,然后再進行事件分發,詳細分發過程稍后會給出。
2、onInterceptTouchEvent(MotionEvent event) --- 攔截事件
onInterceptTouchEvent(MotionEvent event) 方法只存在于ViewGroup當中,是用來對布局容器內子View的事件進行攔截的,如果父容器View對事件進行了攔截,即return true,則子View不會收到任何事件分發。
3、onTouchEvent(MotionEvent event) --- 處理消費事件
onTouchEvent(MotionEvent event)方法如果返回true,則表示該事件被當前View給消費掉了,它的父View的onTouchEvent()后續都不會得到調用,而是通過dispatchTouchEvent()逐級向上返回true到Activity;如果沒人消費該事件,都返回false,則最終會交給Activity去進行處理。
在大致了解了dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent的作用之后,現在我們最需要理清的就是這三者之間的調用關系如何,為此我自己寫了一個測試Demo,界面如下:
屏幕中有ViewGroupA、ViewGroupB、ViewC,依次進行嵌套
測試代碼如下:
<com.android.hanyee.widgets.ViewGroupA xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/viewGroupA"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@android:color/white">
android:id="@+id/viewGroupB"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="60dp"
android:orientation="vertical"
android:background="@android:color/holo_blue_dark">
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="60dp"
android:background="@android:color/holo_green_dark" />
public class ViewGroupA extends LinearLayout {
public ViewGroupA(Context context) {
super(context);
}
public ViewGroupA(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ViewGroupA(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.d("hanyee", this.getClass().getSimpleName() + " onInterceptTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
boolean result = super.onInterceptTouchEvent(ev);
Log.d("hanyee", this.getClass().getSimpleName() + " onInterceptTouchEvent return super.onInterceptTouchEvent(ev)=" + result);
return result;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
boolean result = super.dispatchTouchEvent(ev);
Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent return super.dispatchTouchEvent(ev)= " + result);
return result;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
boolean result = super.onTouchEvent(ev);
Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent return super.onTouchEvent(ev)=" + result);
return result;
}
}
public class ViewGroupB extends LinearLayout {
public ViewGroupB(Context context) {
super(context);
}
public ViewGroupB(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ViewGroupB(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.d("hanyee", this.getClass().getSimpleName() + " onInterceptTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
boolean result = super.onInterceptTouchEvent(ev);
Log.d("hanyee", this.getClass().getSimpleName() + " onInterceptTouchEvent return super.onInterceptTouchEvent(ev)=" + result);
return result;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
boolean result = super.dispatchTouchEvent(ev);
Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent return super.dispatchTouchEvent(ev)= " + result);
return result;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
boolean result = super.onTouchEvent(ev);
Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent return super.onTouchEvent(ev)=" + result);
return result;
}
}
public class ViewC extends View {
public ViewC(Context context) {
super(context);
}
public ViewC(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ViewC(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
boolean result = super.dispatchTouchEvent(ev);
Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent return super.dispatchTouchEvent(ev)= " + result);
return result;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
boolean result = super.onTouchEvent(ev);
Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent return super.onTouchEvent(ev)=" + result);
return result;
}
}
測試情景1:ViewGroupA、ViewGroupB、ViewC都沒有消費事件
測試結果如下圖:
由圖中log可以看出,如果沒有任何view消費事件的話,事件的傳遞順序如下:
ViewGroupA.dispatchTouchEvent -> ViewGroupA.onInterceptTouchEvent(return false, 沒有進行攔截) -> ViewGroupB.dispatchTouchEvent -> ViewGroupB.onInterceptTouchEvent(return false, 沒有進行攔截) -> ViewC.dispatchTouchEvent -> ViewC.onTouchEvent(return false, 沒有消費) -> ViewC.dispatchTouchEvent(return false, 將onTouchEvent的處理結果回傳給ViewGroupB) -> ViewGroupB.onTouchEvent(return false, 也沒有消費) -> ViewB.dispatchTouchEvent(return false, 將onTouchEvent的處理結果回傳給ViewGroupA) -> ViewGroupA.onTouchEvent(return false, 也沒有消費) -> ViewA.dispatchTouchEvent(return false, 最終將onTouchEvent的處理結果回傳給Activity) -> Activity對事件進行最終處理
看到這里大伙可能會有些疑問,怎么就只有Down事件,而沒有后續的Move、Up等事件,這是因為沒有任何子View消費Down事件,Down事件最終被最外層的Activity給處理掉了,所以后續的所有Move、Up等事件都不會再分發給子View了,這里在后面的源碼分析時會提到。
測試情景2:ViewC消費了事件
測試結果如下圖:
由圖中的log可以看出,一旦ViewC消費了Down事件,它的父容器ViewGroupB,祖父容器ViewGroupA的onTouchEvent都不會被調用了,而是直接通過dispatchTouchEvent將Down以及后續的Move、Up事件的處理結果返回至Activity。
測試情景3:僅點擊ViewGroupB,讓ViewGroupB消費事件
測試結果如下圖:
從圖中log可以看出,如果點擊ViewGroupB,事件根本就不會傳遞到ViewC,ViewGroupB在消費了Down事件之后,再直接由父容器ViewGroupA的dispatchTouchEvent將ViewGroupB的onTouchEvent處理結果true回傳給Activity,接下來后續的Move、Up事件都只會傳遞至ViewGroupB,而不會分發給ViewC。
測試情景4:讓ViewGroupB對事件進行攔截
測試結果如圖:
從圖中log可以看出,如果ViewGroupB的onInterceptTouchEvent 返回true,對子view的事件進行攔截,則ViewC不會收到任何的點擊事件,事件流變成了ViewGroupA -->ViewGroupB --> ViewGroupA,而沒有經過ViewC
通過上述幾種情景,我們可以大致了解,ViewGroupA的dispatchTouchEvent最先被調用,主要負責事件分發,然后會調用其onInterceptTouchEvent,如果返回true,則后續的ViewGroupB、ViewC都不會收到任何的點擊事件,相反如果返回false,就放棄攔截事件,接著會遍歷調用子View的dispatchTouchEvent方法將事件分發給ViewGroupB,如果ViewGroupB也沒有攔截事件,則又會遍歷調用子View的dispatchTouchEvent方法將事件分發給ViewC,如果ViewC在onTouchEvent中消費了事件返回true,則會將true通過dispatchTouchEvent方法逐級返回給其父容器直至Activity中,而且不會調用各個父容器對應的onTouchEvent方法,如果子View在onTouchEvent中沒消費事件返回false,則通過dispatchTouchEvent方法將false返回給ViewGroupB,ViewGroupB就知道子View沒有消費事件,就會調用自己的onTouchEvent來處理該事件,然后同理遞歸著ViewC在onTouchEvent中對于事件的處理邏輯,直到ViewGroupA將事件處理完反饋給Activity。
前面列了這么多現象,并歸納總結出以上dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent之間的調用關系,相信大家對于Android事件的分發機制已經有了較為清晰的認識,但作為一名程序員,知其然,還得知其所以然,下面就帶領大家一起研讀下源碼,看看到底為啥是這樣的調用關系。從上面的情景log中大家應該可以看出,事件分發機制的最初始的入口就是ViewGroup的dispatchTouchEvent,下面就看看其代碼:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
// If the event targets the accessibility focused view and this is it, start
// normal event dispatch. Maybe a descendant is what will handle the click.
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;
// 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);
resetTouchState();
}
// 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;
}
// If intercepted, start normal event dispatch. Also if there is already
// a view that is handling the gesture, do normal event dispatch.
if (intercepted || mFirstTouchTarget != null) {
ev.setTargetAccessibilityFocus(false);
}
// Check for cancelation.
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 = 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);
// 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;
}
// 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();
}
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) {
// No touch targets so treat this as an ordinary 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;
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;
}
}
// 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;
}
這方法看似比較長,但我們只挑比較重要的點來看,在第32行會根據disallowIntercept來判斷是否對子view來進行事件攔截,子view可以通過調用requestDisallowInterceptTouchEvent()方法來改變其值,如果可以進行攔截,則會調用onInterceptTouchEvent()方法,根據其返回值來判斷需不需要對子View進行攔截,默認情況下onInterceptTouchEvent()方法返回的是false,所以如果我們在自定義View時如果想攔截的話,可以重寫這個方法返回true就行了。
然后在第58行的if條件中,會根據是否取消canceled以及之前的是否攔截的標志intercepted來判斷是否走進下面的邏輯代碼塊,這里我們只看intercepted,如果沒有攔截,則會進入if后面的邏輯代碼塊,直到第89行的for循環,我們會看到ViewGroup在對所有子View進行遍歷,以方便接下來的事件分發,再看到107、108行的判斷,canViewReceivePointerEvents()用來判斷是否該View能夠接受處理事件,
private static boolean canViewReceivePointerEvents(View child) {
return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE
|| child.getAnimation() != null;
}
可以看到只有當view處于可見狀態且沒有做動畫時才能接收處理事件,再看isTransformedTouchPointInView()是用來判斷當前事件是否觸發在該view的范圍之內,這里我們可以回想前面的測試情景3,當我們點擊ViewGroupB時,ViewC完全沒有收到任何事件,就是因為點擊事件不在ViewC的范圍之類,在isTransformedTouchPointInView()進行判斷時就給過濾掉了,所以ViewC不會收到任何分發的事件。再看看第122行,會調用dispatchTransformedTouchEvent()來將事件分發給對應的view進行處理,讓我們進入其方法體看看,
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
// Canceling motions is a special case. We don't need to perform any transformations
// or filtering. The important part is the action, not the contents.
final int oldAction = event.getAction();
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;
}
// Calculate the number of pointers to deliver.
final int oldPointerIdBits = event.getPointerIdBits();
final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
// If for some reason we ended up in an inconsistent state where it looks like we
// might produce a motion event with no pointers in it, then drop the event.
if (newPointerIdBits == 0) {
return false;
}
// If the number of pointers is the same and we don't need to perform any fancy
// irreversible transformations, then we can reuse the motion event for this
// dispatch as long as we are careful to revert any changes we make.
// Otherwise we need to make a copy.
final MotionEvent transformedEvent;
if (newPointerIdBits == oldPointerIdBits) {
if (child == null || child.hasIdentityMatrix()) {
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
event.offsetLocation(offsetX, offsetY);
handled = child.dispatchTouchEvent(event);
event.offsetLocation(-offsetX, -offsetY);
}
return handled;
}
transformedEvent = MotionEvent.obtain(event);
} else {
transformedEvent = event.split(newPointerIdBits);
}
// 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);
}
// Done.
transformedEvent.recycle();
return handled;
}
我們看到在方法的末尾第55行,如果child為Null,則會調用ViewGroup的父類View的dispatchTouchEvent,否則就會調用child自身的dispatchTouchEvent方法進行事件分發處理。如果child是ViewGroup,則會又遞歸調用ViewGroup的dispatchTouchEvent方法邏輯進行事件分發,如果是View,則跟child為Null情況一樣,都是會調到View的dispatchTouchEvent方法,接下來我們看看View的dispatchTouchEvent方法,
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();
}
if (onFilterTouchEventForSecurity(event)) {
//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;
}
同樣我們撿重點的看,第23行用來做過濾,看是否有窗口覆蓋在上面,第27~29行三個判斷條件說明了,當View的touch事件監聽器不為空,View是enable狀態,且touch事件監聽回調方法onTouch方法返回true三個條件同時滿足時,則會最終返回true,而且第33行的onTouchEvent方法都不會得到執行,這說明View的OnTouchListener監聽回調的優先級要高于onTouchEvent,如果我們給View設置了OnTouchListener監聽,并且在回調方法onTouch()中返回true,View的onTouchEvent就得不到執行,其dispatchTouchEvent方法就會直接返回true給父容器,相反如果返回false,或者沒有設置OnTouchListener監聽,才會執行onTouchEvent()方法對分發來的事件進行處理。接著再去看看onTouchEvent()中如何對事件進行處理的,
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return (((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
(viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
switch (action) {
case MotionEvent.ACTION_UP:
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
// take focus if we don't have it already and we should in
// touch mode.
boolean focusTaken = false;
if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
focusTaken = requestFocus();
}
if (prepressed) {
// The button is being released before we actually
// showed it as pressed. Make it show the pressed
// state now (before scheduling the click) to ensure
// the user sees it.
setPressed(true, x, y);
}
if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
// This is a tap, so remove the longpress check
removeLongPressCallback();
// Only perform take click actions if we were in the pressed state
if (!focusTaken) {
// Use a Runnable and post this rather than calling
// performClick directly. This lets other visual state
// of the view update before click actions start.
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
performClick();
}
}
}
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
if (prepressed) {
postDelayed(mUnsetPressedState,
ViewConfiguration.getPressedStateDuration());
} else if (!post(mUnsetPressedState)) {
// If the post failed, unpress right now
mUnsetPressedState.run();
}
removeTapCallback();
}
mIgnoreNextUpEvent = false;
break;
case MotionEvent.ACTION_DOWN:
mHasPerformedLongPress = false;
if (performButtonActionOnTouchDown(event)) {
break;
}
// Walk up the hierarchy to determine if we're inside a scrolling container.
boolean isInScrollingContainer = isInScrollingContainer();
// For views inside a scrolling container, delay the pressed feedback for
// a short period in case this is a scroll.
if (isInScrollingContainer) {
mPrivateFlags |= PFLAG_PREPRESSED;
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
mPendingCheckForTap.x = event.getX();
mPendingCheckForTap.y = event.getY();
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
// Not inside a scrolling container, so show the feedback right away
setPressed(true, x, y);
checkForLongClick(0);
}
break;
case MotionEvent.ACTION_CANCEL:
setPressed(false);
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
case MotionEvent.ACTION_MOVE:
drawableHotspotChanged(x, y);
// Be lenient about moving outside of buttons
if (!pointInView(x, y, mTouchSlop)) {
// Outside button
removeTapCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
// Remove any future long press/tap checks
removeLongPressCallback();
setPressed(false);
}
}
break;
}
return true;
}
return false;
}
從第716行可以看出,當View為disable狀態,而又clickable時,是會消費掉事件的,只不過在界面上沒有任何的響應。第1822行,關于TouchDelegate,根據對官方文檔的理解就是說有兩個View, ViewB在ViewA中,ViewA比較大,如果我們想點擊ViewA的時候,讓ViewB去響應點擊事件,這時候就需要使用到TouchDelegate, 簡單的理解就是如果該View有自己的事件委托處理人,就交給委托人處理。從第24~26行可以看出,只有當View是可點擊狀態時,才會進入對應各種事件的詳細處理邏輯,否則會直接返回false,表明該事件沒有被消費。在第59行,可以看到在Action_Up事件被觸發時,會執行performClick(),也就是View的點擊事件,由此可知,view的onClick()回調是在Action_Up事件中被觸發的。第134行直接返回了true,可以看出只要View處于可點擊狀態,并且進入了switch的判斷邏輯,就會被返回true,表明該事件被消費掉了,也就是說只要View是可點擊的,事件傳到了其OnTouchEvent,都會被消費掉。而平時我們在調用setOnClickListener方法給View設置點擊事件監聽時,都會將其點擊狀態修改為可點擊狀態。
public void setOnClickListener(@Nullable OnClickListener l) {
if (!isClickable()) {
setClickable(true);
}
getListenerInfo().mOnClickListener = l;
}
追溯完View的事件分發流程,我們再返回到ViewGroup的dispatchTouchEvent方法的122行,如果對應得child消費了點擊事件,就會通過對應的dispatchTouchEvent方法返回true并最終在122行使得條件成立,然后會進入到138行,調用addTouchTarget對newTouchTarget進行賦值,并且mFirstTouchTarget跟newTouchTarget的值都一樣,然后將alreadyDispatchedToNewTouchTarget置為true
private TouchTarget addTouchTarget(View child, int pointerIdBits) {
TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
然后來到了163行,由于mFirstTouchTarget和newTouchTarget在addTouchTarget中都被賦值了,所以會直接進入172行的while循環,由于之前在138、139行對mFirstTouchTarget、newTouchTarget、alreadyDispatchedToNewTouchTarget都賦值了,使得174行條件成立,所以就直接返回true了,至此,ViewGroup就完成了對子View的遍歷及事件分發,由于事件被消費掉了,所以ViewGroup對應的所有外圍容器都會遞歸回調dispatchTouchEvent將true傳遞給Activity,到這也就解釋了測試情景2的產生原理。在Down相關事件被消費掉之后,后續的Move、Up事件在dispatchTouchEvent方法的68~70行不符合判斷條件,直接會來到179行的dispatchTransformedTouchEvent方法繼續進行分發,待子View進行消費。
如果在ViewGroup的dispatchTouchEvent方法第58行被攔截了(對應測試情景4),或者107~108行不成立(對應測試情景3),或者122行返回false(即子View沒有消費事件,對應測試情景1),則會直接進入到第163行,這時mFirstTouchTarget肯定為空,所以會又調用dispatchTransformedTouchEvent方法,而且傳進去的child為空,最終就會直接走到dispatchTransformedTouchEvent方法的55行,然后調用super.dispatchTouchEvent,之后的處理邏輯跟前面調View的dispatchTouchEvent邏輯一樣。
終上所述,整個Android的事件分發機制可以大致概括成如下的流程圖
PS:以上相關的系統代碼均為Android6.0的系統源碼,整個Android事件分發機制還算有點復雜,完全給整明白寫下這篇文章還費了些時間,中間查閱了一些資料,可能有些地方還存在些理解偏差,還請大家指出相互學習進步