Activity對事件分發(fā)的處理
點擊事件產(chǎn)生之后锋叨,最先傳遞給當前Activity产场,由Activity的dispatchTouchEvent進行分發(fā)。
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
很明顯臼疫,Activity直接交由Window去分發(fā)万搔,如果返回的是true,說明事件被處理了官帘,事件就結(jié)束了瞬雹;如果返回的是false,說明事件沒有人處理刽虹,那么Activity就調(diào)用自己的onTouchEvent方法進行處理酗捌。
public abstract boolean superDispatchTouchEvent(MotionEvent event);
跟進Window類可以看到,superDispatchTouchEvent是個抽象方法涌哲。
mWindow = new PhoneWindow(this);
查找Activity的成員變量mWindow的初始化過程胖缤,發(fā)現(xiàn)mWindow是PhoneWindow對象。于是查看PhoneWindow類的superDispatchTouchEvent方法阀圾。
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
這里PhoneWindow直接把點擊事件交給mDecor進行分發(fā)哪廓。mDecor是一個DecorView對象,DecorView是window里的頂級View初烘。在Activity里調(diào)用setContentView就是將layout的View設(shè)置為DecorView的子View涡真。
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
而類DecorView繼承自FrameLayout。superDispatchTouchEvent方法直接調(diào)用了父類的dispatchTouchEvent方法進行分發(fā)肾筐,即調(diào)用ViewGroup的dispatchTouchEvent方法哆料。
ViewGroup對事件分發(fā)的處理
ViewGroup接收到事件之后,如果不攔截吗铐,就繼續(xù)向子View分發(fā)东亦。如果攔截,則調(diào)用onTouchEvent對事件進行處理唬渗,ViewGroup是View的子類典阵,ViewGroup本身是沒有onTouchEvent方法的奋渔,調(diào)用的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;
}
這里要調(diào)用onInterceptTouchEvent判斷是否攔截要先滿足兩個if的條件他巨。
首先是事件類型為ACTION_DOWN或者mFirstTouchTarget!=null充坑,從后面源碼可以知道當有子View成功處理了該事件的時候會調(diào)用addTouchTarget方法將mFirstTouchTarget賦值為該子View,也就是說mFirstTouchTarget!=null意味著這一系列的點擊事件的ACTION_DOWN已經(jīng)有子View進行處理了染突。因此如果ViewGroup攔截了ACTION_DOWN捻爷,后續(xù)的ACTION_MOVE、ACTION_UP等事件就會直接交給ViewGroup處理份企。
第二個if是FLAG_DISALLOW_INTERCEPT標志位也榄,可以調(diào)用requestDisallowInterceptTouchEvent方法設(shè)置了該標志位。按照源碼司志,假設(shè)子View處理了一系列事件的ACTION_DOWN甜紫,這時候mFirstTouchTarget!=null,默認是會調(diào)用ViewGroup的onInterceptTouchEvent方法判斷是否攔截后續(xù)的ACTION_MOVE骂远、ACTION_UP等事件的囚霸,而子View可以通過設(shè)置FLAG_DISALLOW_INTERCEPT標志位來拒絕ViewGroup插手這一系列事件。
而對ACTION_DOWN事件無效激才,因為在ACTION_DOWN事件分發(fā)的時候拓型,會重置該標志位。
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();
}
在分發(fā)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循環(huán)遍歷子View东帅,通過canViewReceivePointerEvents和isTransformedTouchPointInView過濾掉不能接收事件的子View压固。canViewReceivePointerEvents判斷View是否可見或者正在執(zhí)行動畫,isTransformedTouchPointInView判斷點擊是否在View的范圍中靠闭,兩個條件同時滿足的View才可以接收到事件邓夕。
然后通過dispatchTransformedTouchEvent方法將事件分發(fā)到子View。
if (child == null) {
handled = super.dispatchTouchEvent(transformedEvent);
} else {
...
handled = child.dispatchTouchEvent(transformedEvent);
}
dispatchTransformedTouchEvent方法返回子View的處理情況阎毅。如果如果子View已經(jīng)處理焚刚,返回true,則走進if分支調(diào)用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沒有處理,調(diào)用dispatchTransformedTouchEvent(ev, canceled, null,TouchTarget.ALL_POINTER_IDS)方法碳柱,結(jié)合前面dispatchTransformedTouchEvent方法的代碼可以知道當child為null時捡絮,調(diào)用super.dispatchTouchEvent方法,即View類的dispatchTouchEvent方法莲镣。強調(diào)一下福稳,這個dispatchTouchEvent不是子View的方法,而是ViewGroup繼承的View類的方法瑞侮,因此這里是由ViewGroup處理事件的圆。
View對事件分發(fā)的處理
從ViewGroup的dispatchTouchEvent方法分析可以知道,最后都會調(diào)用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中各種監(jiān)聽事件的聚合類钮糖,設(shè)置一些listener的時候就會初始化梅掠。
因此這里邏輯為:如果View設(shè)置了OnTouchListener,就先交給OnTouchListener處理店归,如果onTouchEvent返回true阎抒,就消費掉了事件。如果沒有消費掉該事件消痛,則調(diào)用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狀態(tài)時谴古,如果CLICKABLE或LONG_CLICKABLE為true仍然會消費掉事件质涛。
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
如果設(shè)置了代理稠歉,則交給代理處理,如果代理消費了事件汇陆,則返回true怒炸。否則繼續(xù)往下走。
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中教寂,會觸發(fā)post(mPerformClick)捏鱼。
private final class PerformClick implements Runnable {
@Override
public void run() {
performClick();
}
}
PerformClick是Runnable的子類,run方法中調(diào)用了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設(shè)置了OnClickListener导梆,則會調(diào)用onClick回調(diào)方法。