1、事件概念
當發生點擊事件時,大致的調用順序是先調用最外層View的dispatchTouchEvent方法,然後調用onInterceptTouchEvent方法,再調用onTouchEvent方法;
分發、攔截、消費,一個事件的所經歷的就是這些處理的組合;
Activity和View沒有onInterceptTouchEvent事件;
1.1、分發
表示事件是否會繼續分發出去,默認返回false,返回true時表示事件不會再繼續分發,甚至都不會分發到自身的onTouchEvent方法;
1.2、攔截
對事件傳遞做攔截,表示當前層級的View需要處理這個事件,將事件攔截下來,直接派給自己的onTouchEvent方法去處理,如果onTouchEvent方法處理了並且返回true,這個事件就結束了,如果onTouchEvent方法返回false,該事件還會繼續傳遞到上層ViewGroup的onTouchEvent方發去處理;
1.3、消費
消費事件,如果該方法返回了true,表示對事件消費掉了,事件終止,如果返回false,事件會繼續傳遞給上層ViewGroup方法處理;
2、關鍵方法
2.1、dispatchTouchEvent
分發事件,當該方法返回true時,該View不會繼續分發事件,包括該事件不會繼續分發到該View的onInterceptTouchEvent方法和onTouchEvent方法;
2.2、onInterceptTouchEvent
攔截事件的傳遞,是否會繼續向子View、子ViewGroup傳遞,當該方法返回true時,事件不會繼續向子View、子ViewGroup傳遞,相當於父級View把事件在此處截斷了;
2.3、onTouchEvent
消費事件,對點擊事件做相應的點擊響應處理,具體執行點擊後的操作,如果子View不做處理,即返回false,該事件還會繼續傳遞到父View的onTouchEvent方法去處理,直到傳遞到組外層;
如果該方法返回true,表示這個事件被消費掉了,這個事件就此終止了,不會再有任何傳遞;
對於Activity的onTouchEvent事件,如果內部的控件沒有對事件做任何處理,事件最終都會回到Activity的onTouchEvent方法去處理;
3、調用流程圖
4、源碼
4.1、dispatchTouchEvent
4.1.1、Activity
// Activity
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
public Window getWindow() {
return mWindow;
}
// attach方法中初始化mWindow對象
final void attach(Context context, ActivityThread aThread, ...) {
...
mWindow = new PhoneWindow(this, window, activityConfigCallback);
...
}
// PhoneWindow
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
// DecorView
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
Activity中的dispatchTouchEvent()方法中首先判斷點擊事件是否爲按下,並調用onUserInteraction()方法,該方法爲一個空實現;
其次會執行window的superDispatchTouchEvent()方法,在Activity的attach()方法中mWindow是new的一個PhoneWindow對象,在PhoneWindow中又是調用DecorView的superDispatchTouchEvent()方法,DecorView是一個繼承自FrameLayout的類,所以他調用的父類的dispatchTouchEvent()方法將追溯到ViewGroup的dispatchTouchEvent()方法中,當子View和ViewGroup都不處理事件,即dispatchTouchEvent()方法都返回false,則會去調用Activity的onTouchEvent()方法處理事件;
4.1.2、ViewGroup
@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);
}
...
}
首先判斷事件的焦點處理,輸入事件響應,如果有輸入焦點在,則交給輸入去執行OnTouchEvent()事件;
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();
}
...
}
其次判斷事件是否符合應用安全策略,將不符合的事件過濾掉;
當事件是ACTION_DOWN時,調用cancelAndClearTouchTargets()方法清除掉所有關聯的目標,即按下事件被認爲是一整個事件的開始,並且通過調用resetTouchState()方法重置觸摸事件的狀態爲一個新的週期;
這裏也會重置FLAG_DISALLOW_INTERCEPT這個標記位,這個標記位的作用是決定ViewGroup是否攔截除ACTION_DOWN之外的事件,無法攔截ACTION_DOWN事件,因爲在ACTION_DOWN時會重置這個標記位;
// 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);
}
接着判斷是否需要攔截,當事件不是ACTION_DOWN並且mFirstTouchTarget爲空時,直接返回爲true,表示該ViewGroup攔截下來了該事件,說明如果攔截,ViewGroup只能攔截到ACTION_DOWN事件,mFirstTouchTarget爲空表示該ViewGroup沒有子View去處理事件,所以自己攔截下來;
當ACTION_DWON或者mFirstTouchTarget不爲空時,判斷mGroupFlags & FLAG_DISALLOW_INTERCEPT,mGroupFlags是View的標記,FLAG_DISALLOW_INTERCEPT如果該變量設置了,說明該ViewGroup不該攔截事件,返回false,否則就會去調用ViewGroup的onInterceptTouchEvent()方法,ev.setAction(action)重置事件的action,在攔截方法中如果action有發生改變;
接着如果該事件被攔截,並且mFirstTouchTarget不爲空(即事件被子View消費),將該事件的可訪問性焦點標記爲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 accessibility 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 = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null && isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(preorderedList, children, 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;
}
}
}
接下來會去遍歷子View,將事件分發到子View處理,判斷子View是有可訪問性焦點並且焦點在子View本身、通過調用canViewReceivePointerEvents()方法和isTransformedTouchPointInView()方法判斷View是否可以接受事件(滿足兩個條件:事件發生在View的區域,子View沒有正在播放的動畫)、調用dispatchTransformedTouchEvent()方法篩選出可以接受事件的子View,結束循環,事件成功交給子View;
在調用dispatchTransformedTouchEvent()方法是,第三個參數不爲空,即子View不爲空時,調用子View的dispatchTouchEvent()方法去處理;
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
調用addTouchEvent()方法,爲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);
} 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;
}
}
如果沒有找到合適的可以接受事件的子View,則mFirstTouchTarget沒有賦值,則ViewGroup自己調用dispatchTransformedTouchEvent()方法處理,第三個參數View child爲null,查看該方法,當child爲null時,調用父類的dispatchTouchEvent()方法,即調用View的dispatchTouchEvent()方法;
4.1.3、View
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);
}
...
}
View的dispatchTouchEvent()方法,會先判斷該事件是否爲帶有焦點處理的,例如EditText的輸入響應、Button的點擊響應等,如果沒有需要處理的則直接返回false,如果有則設置相關標記,繼續進行正常的事件派發;
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(event, 0);
}
檢查是否有輸入性的事件,如果有,表示該View屬於一個輸入類型的View,則去調用該輸入序列的onTouchEvent()方法去處理輸入事件;
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;
}
}
public boolean onFilterTouchEventForSecurity(MotionEvent event) {
//noinspection RedundantIfStatement
if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
// Window is obscured, drop this touch.
return false;
}
return true;
}
接着調用onFilterTouchEventForSecurity()方法過濾不符合應用安全策略的事件,如果可以繼續被分發則返回true,否則返回false;
接着判斷View的各種狀態,以及是否被滾動條事件消費掉等,handleScrollBarDragging()方法處理拖動滾動條事件,當該方法處理完之後返回true表示消費掉該事件;
接着判斷mOnTouchListener是否爲空,不爲空表示用戶自定義了OnTouchEvent事件(通過調用setOnTouchListener()方法),則會調用OnTouchListener的onTouchEvent()方法去處理事情並返回,所以設置OnTouchListener的優先級要高於本身的OnTouchEvent事件;
最後判斷本身OnTouchEvent()方法處理返回;
if (!result && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
如果最終事件沒有處理並且是輸入控件,則將該輸入序列掛起爲未處理,並重置該事件需要被忽略;
if (actionMasked == MotionEvent.ACTION_UP ||
actionMasked == MotionEvent.ACTION_CANCEL ||
(actionMasked == MotionEvent.ACTION_DOWN && !result)) {
stopNestedScroll();
}
最終手勢事件結束並且處理結果爲false時,調用stopNestedScroll()方法,停止正在進行的嵌套滾動;
4.2、onInterceptTouchEvent
4.2.1、ViewGroup
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
&& ev.getAction() == MotionEvent.ACTION_DOWN
&& ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
&& isOnScrollbarThumb(ev.getX(), ev.getY())) {
return true;
}
return false;
}
該方法判斷是否需要對事件進行攔截下來處理,通過判斷事件的來源、是否爲ACTION_DOWN事件、是否是Button按鈕按下以及滾動條事件等,來決定是否需要將該事件攔截下來;
4.3、onTouchEvent
4.3.1、Activity
public boolean onTouchEvent(MotionEvent event) {
if (mWindow.shouldCloseOnTouch(this, event)) {
finish();
return true;
}
return false;
}
當屏幕觸摸事件沒有被任何子View消費時,最終會調用該方法來處理,該方法默認實現是返回爲false;
4.3.2、View
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return clickable;
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
...
}
對View的各種標識進行判斷,該View爲可點擊、長按的狀態,clickable爲true,當View爲禁用點擊時DISABLED,也會處理該事件,只是沒有具體的響應,將狀態設置爲未點擊,並刷新Drawable狀態;
如果設置了觸摸代理,即mTouchDelegate不爲空,則交給mTouchDelegate對象去處理OnTouchEvent()事件並返回true,表示事件被消費,不再繼續傳遞;
case MotionEvent.ACTION_UP:
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
if ((viewFlags & TOOLTIP) == TOOLTIP) {
handleTooltipUp();
}
if (!clickable) {
removeTapCallback();
...
}
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
...
if (prepressed) {
...
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) {
...
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
performClickInternal();
}
}
}
...
if (prepressed) {
postDelayed(mUnsetPressedState, ViewConfiguration.getPressedStateDuration());
} else if (!post(mUnsetPressedState)) {
// If the post failed, unpress right now
mUnsetPressedState.run();
}
removeTapCallback();
}
mIgnoreNextUpEvent = false;
break;
如果該View有長按提示效果,則先處理掉該長按提示事件;
如果當前View是不可點擊的,則清除掉View的各種相關狀態;
PFLAG_PREPRESSED狀態爲嵌套滾動View,如果View被嵌套在一個滾動的View中,會檢查其父View是否攔截事件,如果父View沒有攔截則開始處理,調用setPressed()方法設置按下狀態讓用戶明確感受到;
判斷mHasPerformedLongPress和mIgnoreNextUpEvent是否爲處理過長按事件,如果不是長按,調用removeLongPressCallback()方法移除掉長按事件的回調,接着開啓一個子線程(new PerformClick())去執行click事件,如果異步執行失敗,則直接同步執行,接着調用ViewConfiguration.getPressedStateDuration()獲得按下效果的顯示時間設置View的顯示狀態(API 28 顯示時間爲64ms),同樣post失敗之後直接調用,移除掉Tap的回調,重置View狀態;
performClickInternal()方法中調用performClick()方法,在這裏會判斷onClickListener是否爲空,不爲空則執行onClickListener的onClick()方法,即用戶設置的onClickListener事件,優先級最低;
case MotionEvent.ACTION_DOWN:
if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
}
mHasPerformedLongPress = false;
if (!clickable) {
checkForLongClick(0, x, y);
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, x, y);
}
break;
按下事件,如果View不可點擊,檢查長按事件,如果是則直接跳出,接着會檢查是否在滾動容器中,如果是設置mPrivateFlags狀態,接着new CheckForTap去檢查是Tap還是長按事件,如果在滾動View中嵌套,則通過ViewConfiguration.getTapTimeout()去獲取延遲返回時間,設置在規定時間內,如果用戶沒有移動則說明是點擊事件(API 28中爲100ms);
case MotionEvent.ACTION_CANCEL:
if (clickable) {
setPressed(false);
}
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
break;
取消手勢,重置View所有狀態;
case MotionEvent.ACTION_MOVE:
if (clickable) {
drawableHotspotChanged(x, y);
}
// Be lenient about moving outside of buttons
if (!pointInView(x, y, mTouchSlop)) {
// Outside button
// Remove any future long press/tap checks
removeTapCallback();
removeLongPressCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
}
break;
移動手勢,通過調用drawableHotspotChanged()方法,實時更新傳遞移動的座標位置;
接着判斷當前移動的手勢是否在View中,如果移除手指,則移除掉對應的回調;
本文參考:
《Android開發藝術探索》
2019移動開發者峯會-陳冰-Android移動端手勢交互原理