android的事件分發(fā)主要在view和viewGroup中康谆,那么android是怎么進行事件處理的通過源碼來一探究竟领斥。
首先所有事件都會調(diào)用dispatchTouchEvent方法。
View的事件分發(fā)
先看View的dispatchTouchEvent方法:
public boolean dispatchTouchEvent(MotionEvent 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;
}
...
return result;
}
看到方法中會先去判斷l(xiāng)i.mOnTouchListener是否被設(shè)置過沃暗,并且調(diào)用li.mOnTouchListener的onTouch方法月洛,如果沒有設(shè)置過則調(diào)用onTouchEvent方法,那么可以發(fā)現(xiàn)li.mOnTouchListener的優(yōu)先級高于onTouchEvent孽锥。
li.mOnTouchListener就是view.setOnTouchListener(new View.OnTouchListener())時進行的設(shè)置嚼黔,這里不再詳細展開。
接著來分析onTouchEvent方法惜辑,還是來看下源碼:
public boolean onTouchEvent(MotionEvent event) {
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的狀態(tài)是否為disable唬涧,如果為disable則當前view也會消耗掉點擊事件,但是不會觸發(fā)點擊事件回調(diào)盛撑。
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
這里判斷是否設(shè)置過mTouchDelegate并執(zhí)行onTouchEvent碎节,類似OnTouchListener,這里不深入講解抵卫。
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
(viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
switch (action) {
case MotionEvent.ACTION_UP:
...
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
performClick();
}
}
}
...
break;
這個一段代碼可以看到只要view設(shè)置CLICKABLE或LONG_CLICKABLE中一個為true狮荔,都會消耗掉這個事件,最后返回true介粘。
在MotionEvent.ACTION_UP狀態(tài)時,會執(zhí)行performClick殖氏,這個方法中會執(zhí)行l(wèi)i.mOnClickListener.onClick方法,代碼如下:
public boolean performClick() {
if (li != null && li.mOnClickListener != null) {
li.mOnClickListener.onClick(this);
result = true;
} else {
result = false;
}
return result;
}
繼續(xù)分析onTouchEvent方法:
case MotionEvent.ACTION_DOWN:
mHasPerformedLongPress = false;
if (isInScrollingContainer) {
mPrivateFlags |= PFLAG_PREPRESSED;
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
mPendingCheckForTap.x = event.getX();
mPendingCheckForTap.y = event.getY();
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
checkForLongClick(0);
}
break;
在MotionEvent.ACTION_DOWN狀態(tài)時姻采,checkForLongClick會驗證是否達到了長按的標準(DEFAULT_LONG_PRESS_TIMEOUT=500ms)雅采,當達到標準后如果設(shè)置了onLongClickListener會調(diào)用li.mOnLongClickListener.onLongClick方法。
case MotionEvent.ACTION_CANCEL:
setPressed(false);
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
在MotionEvent.ACTION_CANCEL狀態(tài)時慨亲,會重置一些狀態(tài)婚瓜。
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;
}
通過這一大段代碼可以發(fā)現(xiàn),是否消耗掉這個事件也就是是否返回true的關(guān)鍵點就是
(viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
(viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
這一大串的判斷巡雨,那么這些狀態(tài)是在什么時候設(shè)置的則是關(guān)鍵點闰渔。
view的LONG_CLICKABLE屬性默認為false,CLICKABLE屬性是否為false則與view的具體類型有關(guān)铐望,向TextView默認為false冈涧,而Button為true茂附。setClickable會設(shè)置view的CLICKABLE屬性,setLongClickable和setContextClickable也同樣會改變LONG_CLICKABLE和CONTEXT_CLICKABLE的屬性督弓。當setOnClickListener時會自動設(shè)置當前view的CLICKABLE屬性為true营曼,setOnLongClickListener和setOnContextClickListener也會分別設(shè)置LONG_CLICKABLE和CONTEXT_CLICKABLE為true。
public void setOnClickListener(@Nullable OnClickListener l) {
if (!isClickable()) {
setClickable(true);
}
getListenerInfo().mOnClickListener = l;
}
ViewGroup的事件分發(fā)
下邊來看ViewGroup的dispatchTouchEvent方法愚隧。
public boolean dispatchTouchEvent(MotionEvent ev) {
...
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// 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;
}
上邊這段代碼可以看到蒂阱,當時間類型為MotionEvent.ACTION_DOWN或mFirstTouchTarget不為null時,才會有機會去執(zhí)行onInterceptTouchEvent方法狂塘,MotionEvent.ACTION_DOWN事件很好理解录煤,那mFirstTouchTarget這個變量通過后邊的代碼可以發(fā)現(xiàn),當事件由ViewGroup的子元素處理時荞胡,mFirstTouchTarget會被賦值指向子元素妈踊,所以當ViewGroup不攔截并由子元素處理且不為MotionEvent.ACTION_DOWN時,onInterceptTouchEvent方法不會被調(diào)用泪漂。
可以看到經(jīng)過上面的判斷后廊营,還會進行一次通過FLAG_DISALLOW_INTERCEPT的判斷,那FLAG_DISALLOW_INTERCEPT這個標記位是怎么設(shè)置的呢萝勤?requestDisallowInterceptTouchEvent這個方法提供了修改這個標志位露筒,一般會在子view中使用這個方法,這也為子view來控制父view提供了一種方式敌卓,當設(shè)置了這個標記位后ViewGroup將無法攔截除了MotionEvent.ACTION_DOWN以外的的其他事件慎式,為什么MotionEvent.ACTION_DOWN會被排除?因為在狀態(tài)為MotionEvent.ACTION_DOWN時ViewGroup會執(zhí)行resetTouchState方法趟径,這個方法會重置FLAG_DISALLOW_INTERCEPT標記位瞬捕,所以在MotionEvent.ACTION_DOWN狀態(tài)時一定會執(zhí)行onInterceptTouchEvent方法。
經(jīng)過上邊代碼后intercepted會獲得一個值舵抹,這個值會影響到后續(xù)代碼,繼續(xù)向下看:
if (!canceled && !intercepted) {
...
final int childrenCount = mChildrenCount;
if (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
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 (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) {
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;
}
}
}
當intercepted為false且不在ACTION_CANCEL狀態(tài)時劣砍,會遍歷這個ViewGroup的子View惧蛹,當view符合可以接受點擊事件和在子view的區(qū)域內(nèi)時,會執(zhí)行dispatchTransformedTouchEvent方法刑枝,這個方法用來讓子元素執(zhí)行dispatchTouchEvent方法香嗓,來具體看下這個方法內(nèi)部實現(xiàn):
if (child == null) {
handled = super.dispatchTouchEvent(transformedEvent);
} else {
handled = child.dispatchTouchEvent(transformedEvent);
}
通過上邊代碼看到當child!=null時會調(diào)用child的dispatchTouchEvent装畅,這個child就是我們從dispatchTransformedTouchEvent方法傳入的靠娱,前邊一個章節(jié)介紹了view的dispatchTouchEvent,這里就會繼續(xù)執(zhí)行view的dispatchTouchEvent邏輯掠兄,這里不再贅述像云,可以再回看一遍上邊關(guān)于view的講解锌雀。
當子view返回true時,也就表明子view會消耗掉這個事件迅诬,那么會執(zhí)行addTouchTarget方法給mFirstTouchTarget賦值并跳出當前遍歷腋逆。
// 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);
}
return handled;
}
當子view都返回了false也就是mFirstTouchTarget == null或者當前ViewGroup并沒有子view時,最終會執(zhí)行dispatchTransformedTouchEvent侈贷,上邊我們已經(jīng)分析了這個方法當child==null時會執(zhí)行自身的super.dispatchTouchEvent惩歉,因為ViewGroup是View的一個子類,這時又回到了View的dispatchTouchEvent方法的邏輯之中俏蛮。
上邊的文章已經(jīng)的詳細的分析了view的事件分發(fā)過程撑蚌,dispatchTouchEvent方法如果事件能夠傳遞那么這個方法一定會調(diào)用,返回結(jié)果受當前的onTouchEvent和下級的dispatchTouchEvent共同作用搏屑,表示是否消耗當前的事件争涌。onInterceptTouchEvent方法只會出現(xiàn)在ViewGroup的子類中,用來判斷是否攔截當前事件睬棚,在某些情況下不會被調(diào)用第煮。onTouchEvent用來處理點擊事件,返回結(jié)果表示是否消耗掉當前事件抑党。
總覽事件分發(fā)過程
主要的分發(fā)邏輯分析完包警,還有一部分邏輯發(fā)生在Activity->Window->PhoneWindow->DecorView。通過一層層的傳遞傳遞到頂層View底靠,頂層View一般來說是一個ViewGroup害晦,就會進入我們文章分析的分發(fā)邏輯之中。當所有view的不響應這個事件時暑中,最終Activity會執(zhí)行onTouchEvent方法壹瘟。
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
至此已經(jīng)完成了android的事件分發(fā)體系的講解,看完后相信會對android 的事件分發(fā)有了進一步的理解鳄逾,希望能夠從文章中獲得你所需要的知識稻轨。感謝觀看。