事件分發的原始碼解析
Activity對事件分發的處理
點選事件產生之後,最先傳遞給當前Activity,由Activity的dispatchTouchEvent進行分發。
public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { onUserInteraction(); } if (getWindow().superDispatchTouchEvent(ev)) { return true; } return onTouchEvent(ev); }
很明顯,Activity直接交由Window去分發,如果返回的是true,說明事件被處理了,事件就結束了;如果返回的是false,說明事件沒有人處理,那麼Activity就呼叫自己的onTouchEvent方法進行處理。
public abstract boolean superDispatchTouchEvent(MotionEvent event);
跟進Window類可以看到,superDispatchTouchEvent是個抽象方法。
mWindow = new PhoneWindow(this);
查詢Activity的成員變數mWindow的初始化過程,發現mWindow是PhoneWindow物件。於是檢視PhoneWindow類的superDispatchTouchEvent方法。
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
這裡PhoneWindow直接把點選事件交給mDecor進行分發。mDecor是一個DecorView物件,DecorView是window裡的頂級View。在Activity裡呼叫setContentView就是將layout的View設定為DecorView的子View。
public boolean superDispatchTouchEvent(MotionEvent event) { return super.dispatchTouchEvent(event); }
而類DecorView繼承自FrameLayout。superDispatchTouchEvent方法直接呼叫了父類的dispatchTouchEvent方法進行分發,即呼叫ViewGroup的dispatchTouchEvent方法。
ViewGroup對事件分發的處理
ViewGroup接收到事件之後,如果不攔截,就繼續向子View分發。如果攔截,則呼叫onTouchEvent對事件進行處理,ViewGroup是View的子類,ViewGroup本身是沒有onTouchEvent方法的,呼叫的View的onTouchEvent方法,因此攔截之後對事件的處理邏輯和View是一致的。
先從dispatchTouchEvent看起,以下判斷是否攔截的部分。
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;
}
這裡要呼叫onInterceptTouchEvent判斷是否攔截要先滿足兩個if的條件。
首先是事件型別為ACTION_DOWN或者mFirstTouchTarget!=null,從後面原始碼可以知道當有子View成功處理了該事件的時候會呼叫addTouchTarget方法將mFirstTouchTarget賦值為該子View,也就是說mFirstTouchTarget!=null意味著這一系列的點選事件的ACTION_DOWN已經有子View進行處理了。因此如果ViewGroup攔截了ACTION_DOWN,後續的ACTION_MOVE、ACTION_UP等事件就會直接交給ViewGroup處理。
第二個if是FLAG_DISALLOW_INTERCEPT標誌位,可以呼叫requestDisallowInterceptTouchEvent方法設定了該標誌位。按照原始碼,假設子View處理了一系列事件的ACTION_DOWN,這時候mFirstTouchTarget!=null,預設是會呼叫ViewGroup的onInterceptTouchEvent方法判斷是否攔截後續的ACTION_MOVE、ACTION_UP等事件的,而子View可以通過設定FLAG_DISALLOW_INTERCEPT標誌位來拒絕ViewGroup插手這一系列事件。
而對ACTION_DOWN事件無效,因為在ACTION_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();
}
在分發ACTION_DOWN事件時,清除了mFirstTouchTarget和mGroupFlags。
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();
}
ViewGroup不攔截點選事件的時候,通過for迴圈遍歷子View,通過canViewReceivePointerEvents和isTransformedTouchPointInView過濾掉不能接收事件的子View。canViewReceivePointerEvents判斷View是否可見或者正在執行動畫,isTransformedTouchPointInView判斷點選是否在View的範圍中,兩個條件同時滿足的View才可以接收到事件。
然後通過dispatchTransformedTouchEvent方法將事件分發到子View。
if (child == null) {
handled = super.dispatchTouchEvent(transformedEvent);
} else {
...
handled = child.dispatchTouchEvent(transformedEvent);
}
dispatchTransformedTouchEvent方法返回子View的處理情況。如果如果子View已經處理,返回true,則走進if分支呼叫addTouchTarget。並將標誌位alreadyDispatchedToNewTouchTarget賦值為true。
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
將子View賦值給mFirstTouchTarget。
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
如果子View沒有處理,呼叫dispatchTransformedTouchEvent(ev, canceled, null,TouchTarget.ALL_POINTER_IDS)方法,結合前面dispatchTransformedTouchEvent方法的程式碼可以知道當child為null時,呼叫super.dispatchTouchEvent方法,即View類的dispatchTouchEvent方法。強調一下,這個dispatchTouchEvent不是子View的方法,而是ViewGroup繼承的View類的方法,因此這裡是由ViewGroup處理事件。
View對事件分發的處理
從ViewGroup的dispatchTouchEvent方法分析可以知道,最後都會呼叫View類的dispatchTouchEvent方法進行處理。
public boolean dispatchTouchEvent(MotionEvent event) {
boolean result = false;
...
final int actionMasked = event.getActionMasked();
if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//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);
}
return result;
}
相對來說,View的dispatchTouchEvent方法比較短比較清晰。ListenerInfo是View中各種監聽事件的聚合類,設定一些listener的時候就會初始化。
因此這裡邏輯為:如果View設定了OnTouchListener,就先交給OnTouchListener處理,如果onTouchEvent返回true,就消費掉了事件。如果沒有消費掉該事件,則呼叫View的onTouchEvent方法進行處理。接下來分段分析onTouchEvent的原始碼。
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);
}
從程式碼中可以看到,當View處於DISABLED狀態時,如果CLICKABLE或LONG_CLICKABLE為true仍然會消費掉事件。
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
如果設定了代理,則交給代理處理,如果代理消費了事件,則返回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) {
...
if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
...
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();
}
}
}
...
}
mIgnoreNextUpEvent = false;
break;
...
}
return true;
}
如果CLICKABLE或者LONGCLICKABLE為true時,最後預設return true,即預設消費掉touch事件。在ACTION_UP中,會觸發post(mPerformClick)。
private final class PerformClick implements Runnable {
@Override
public void run() {
performClick();
}
}
PerformClick是Runnable的子類,run方法中呼叫了performClick方法。
public boolean performClick() {
final boolean result;
final ListenerInfo li = mListenerInfo;
if (li != null && li.mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
li.mOnClickListener.onClick(this);
result = true;
} else {
result = false;
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
return result;
}
如果View設定了OnClickListener,則會呼叫onClick回撥方法。