View 事件分發
事件的種類
手勢類型 | 事件名稱 | 說明 |
---|---|---|
按下 | MotionEvent.ACTION_DOWN | 一切事件的起點、可以有多個 |
移動 | MotionEvent.ACTION_MOVE | 手指移動時持續觸發 |
抬起 | MotionEvent.ACTION_UP | 手指抬起,事件結束 |
取消 | MotionEvent.ACTION_CANCEL | 事件取消,比如ViewGroup搶奪事件 |
事件的傳遞
在手指接觸屏幕那一刻,由屏幕到 Native 層,再由 Native 傳到 Activity 的 dispatchTouchEvent();
我們來看一下Activity 的代碼:
/**
* Called to process touch screen events. You can override this to
* intercept all touch screen events before they are dispatched to the
* window. Be sure to call this implementation for touch screen events
* that should be handled normally.
*
* @param ev The touch screen event.
*
* @return boolean Return true if this event was consumed.
*/
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
// activity無論分發按鍵事件、觸摸事件或者軌跡球事件都會調用Activity#onUserInteraction()
// 重寫該方法可知道用戶用某種方式和你正在運行的activity交互
onUserInteraction();
}
// 如果 getWindow().superDispatchTouchEvent(ev) 返回為 true 則說明事件被 Activity
// 子布局消費掉,事件被處理則返回 true
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
// 如果 Activity 子布局沒有消費該事件,則事件由 Activity 處理
return onTouchEvent(ev);
}
為方便查看,我在代碼中加了注釋,因為我們關心的是 View 的事件分發,所以我們關心的應該是getWindow().superDispatchTouchEvent(ev)
,分發的過程。跟進去我們發現 superDispatchTouchEvent(ev)
在 Window 中是一個抽象方法,在 Android 中 PhoneWindow 是 Window 的唯一實現子類。看一下 PhoneWindow#superDispatchTouchEvent(MotionEvent event)
:
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
發現,PhoneWindow 去調用了 DecorView 的 superDispatchTouchEvent(MotionEvent event)
,再來看一下 DecorView#superDispatchTouchEvent(MotionEvent event)
:
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
發現 DecorView 調用了父親的 dispatchTouchEvent(event);
,DecorView 繼承自 FrameLayout,看一下FrameLayout 發現他并沒有實現該方法,所以,DecorView應該調用的是 Fragment 的父親 ViewGroup 的dispatchTouchEvent(MotionEvent event)
,所以,事件就從屏幕最終傳輸到 View 和 ViewGroup 來分發和處理大概流程如下:
499.jpeg
關鍵方法:
ViewGroup # dispatchTouchEvent
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
...
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;
// 如果是按下事件(新的觸摸動作),或者已經存在處理事件的子View
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
// 檢查是否不允許攔截,由子 view requestDisallowInterceptTouchEvent(true)設置
// 相當于子 view 的尚方寶劍
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
// 允許攔截,該 viewgroup 去嘗試攔截
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;
}
...
// 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;
// 如果不是取消事件,并且該事件沒有被當前 view 攔截,進入分發流程
if (!canceled && !intercepted) {
...
// 如果是按下事件
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);
// 該 view 的直接子 view/viewgroup數量(不包括孫 view)
final int childrenCount = mChildrenCount;
// 還沒有 view 接受按下事件,表示此事件為第一個按下事件
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.
// 創建待遍歷的view列表,按照虛擬 z 軸排序,排序將影響 view 接到事件的順序
final ArrayList<View> preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
// 倒序遍歷每個字 view/viewgroup
for (int i = childrenCount - 1; i >= 0; i--) {
// 分別獲取子 view 及其索引
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, childIndex);
...
// 判斷 view 可見性和是否存在動畫,如果不可見或者因動畫移出該區域
// 則跳過,繼續遍歷
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
// 鏈表中已經存在該view,說明該子view已經接收過按下(初始)
// 的觸摸事件,說明這是一個多點觸摸的情況,
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);
// 在此方法中對事件進行下發或者處理,如果為 true 說明事件被下層子 view
// 消費
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
// 記錄該事件消費時間和子 view 的下標
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();
// 將接受按下事件的 view 加入到 TouchTarget 鏈表, // 同時記錄此 view到 mFirstTouchTarget = target
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
// 按下事件被消費,結束分發
break;
}
...
}
// 將事件分發 view List 清空
if (preorderedList != null) preorderedList.clear();
}// 這里if (newTouchTarget == null && childrenCount != 0) 判斷結束點
// 沒有找到可以消費事件的子 view,事件回歸到上次最近的 Down 事件
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;
}
}// down 事件
} // if (!canceled && !intercepted) { 分發事件結束
// Dispatch to touch targets.
// 經過down事件分發結束,所有子 view 都沒消費該事件
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
// 事件直接由 viewgroup 自己消費
// child = null;dispatchTransformedTouchEvent
// 會直接去調用 view 的 disPatchTouchEvent
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.
// mFirstTouchTarget != null說明已經有 view 拿到了 down 事件,后續事件也交給它
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)) {
// 該TouchTarget已經在前面的情況中被分發處理了,避免重復處理
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.
// 如果為up事件或者hover_move事件(一系列觸摸事件結束),清除記錄的信息
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;
}
ViewGroup # onInterceptTouchEvent
/**
* Implement this method to intercept all touch screen motion events. This
* allows you to watch events as they are dispatched to your children, and
* take ownership of the current gesture at any point.
*
* <p>Using this function takes some care, as it has a fairly complicated
* interaction with {@link View#onTouchEvent(MotionEvent)
* View.onTouchEvent(MotionEvent)}, and using it requires implementing
* that method as well as this one in the correct way. Events will be
* received in the following order:
*
* <ol>
* <li> You will receive the down event here.
* <li> The down event will be handled either by a child of this view
* group, or given to your own onTouchEvent() method to handle; this means
* you should implement onTouchEvent() to return true, so you will
* continue to see the rest of the gesture (instead of looking for
* a parent view to handle it). Also, by returning true from
* onTouchEvent(), you will not receive any following
* events in onInterceptTouchEvent() and all touch processing must
* happen in onTouchEvent() like normal.
* <li> For as long as you return false from this function, each following
* event (up to and including the final up) will be delivered first here
* and then to the target's onTouchEvent().
* <li> If you return true from here, you will not receive any
* following events: the target view will receive the same event but
* with the action {@link MotionEvent#ACTION_CANCEL}, and all further
* events will be delivered to your onTouchEvent() method and no longer
* appear here.
* </ol>
*
* @param ev The motion event being dispatched down the hierarchy.
* @return Return true to steal motion events from the children and have
* them dispatched to this ViewGroup through onTouchEvent().
* The current target will receive an ACTION_CANCEL event, and no further
* messages will be delivered here.
*/
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;
}
View # dispatchTouchEvent
/**
* Pass the touch screen motion event down to the target view, or this
* view if it is the target.
*
* @param event The motion event to be dispatched.
* @return True if the event was handled by the view, false otherwise.
*/
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)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//noinspection SimplifiableIfStatement
// 如果注冊了 onTouchListener 監聽,并且監聽 回調方法中 onTouch() 返回 true 時,該
// 事件被消費,此時不會再執行 onTouchEvent(event),注意:onClickListener() 會在
// onTouchEvent(event) 中調用,所以如果 onTouch() 返回 true 時 click 事件就不會接收到
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
// 如果事件被消費就不會再執行 onTouchEvent(event)
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.
// 如果是up事件(系列觸摸動作的終點),或者是cancel事件,或者是初始事件并且我們沒對它進行處理 // (回憶前面的內容,如果沒有處理down事件,那么也不會收到后面的事件),就停止滾動狀態
if (actionMasked == MotionEvent.ACTION_UP ||
actionMasked == MotionEvent.ACTION_CANCEL ||
(actionMasked == MotionEvent.ACTION_DOWN && !result)) {
stopNestedScroll();
}
return result;
}
View # onTouchEvent()
/**
* Implement this method to handle touch screen motion events.
* <p>
* If this method is used to detect click actions, it is recommended that
* the actions be performed by implementing and calling
* {@link #performClick()}. This will ensure consistent system behavior,
* including:
* <ul>
* <li>obeying click sound preferences
* <li>dispatching OnClickListener calls
* <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
* accessibility features are enabled
* </ul>
*
* @param event The motion event.
* @return True if the event was handled, false otherwise.
*/
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();
// 如果該view被禁用,但是被設置為clickable或longClickable或contextClickable,仍然消耗該事件
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
if ((viewFlags & ENABLED_MASK) == DISABLED) {
// 如果view被禁用且按下狀態為true,取消接下狀態
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;
}
// 如果為該view設置了觸摸事件代理,則轉發到代理處理觸摸事件
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
// 處理了view被禁用和設置了觸摸事件代理的情況。
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
if ((viewFlags & TOOLTIP) == TOOLTIP) {
handleTooltipUp();
}
if (!clickable) {
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
}
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.
// 如果有prepressed或pressed標志
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.
// prepressed狀態表示滾動容器中的點擊檢測還沒有被消息隊列執行,
// 這個時候如果抬起手指說明是一個點擊事件,調用setPressed顯示反饋
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
// 當當前view沒有獲取焦點時才能觸發點擊事件,
// 說明一個可以獲取焦點的view是無法觸發點擊事件的
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();
}
// 使用post來將performClick動作放入隊列中執行來
// 保證其他view視覺上的變化可以在點擊事件被觸發之前被看到
if (!post(mPerformClick)) {
performClickInternal();
}
}
}
// UnsetPressedState為Runnable消息,用于取消view的prepressed或pressed狀態
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
if (prepressed) {
// 取消prepressed狀態
postDelayed(mUnsetPressedState,
ViewConfiguration.getPressedStateDuration());
} else if (!post(mUnsetPressedState)) {
// If the post failed, unpress right now
// 取消pressed狀態
mUnsetPressedState.run();
}
// 清除單擊檢測消息
removeTapCallback();
}
mIgnoreNextUpEvent = false;
break;
case MotionEvent.ACTION_DOWN:
if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
}
mHasPerformedLongPress = false;
if (!clickable) {
checkForLongClick(0, x, y);
break;
}
// 檢查Button點擊事件的特殊情況
// 只是處理了事件來源是鼠標的特殊情況。
if (performButtonActionOnTouchDown(event)) {
break;
}
// Walk up the hierarchy to determine if we're inside a scrolling container.
// 向上遍歷view以檢查是否處在一個可滾動的容器中
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) {
// 新建一個對象用于檢測單擊事件
// 它是一個Runnable,用于延遲執行單擊檢測的任務:
mPendingCheckForTap = new CheckForTap();
}
mPendingCheckForTap.x = event.getX();
mPendingCheckForTap.y = event.getY();
// 利用消息隊列來延遲發送檢測單擊事件的方法,
// 延遲時間為getTapTimeout設置的超時
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;
case MotionEvent.ACTION_CANCEL:
if (clickable) {
setPressed(false);
}
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
break;
case MotionEvent.ACTION_MOVE:
if (clickable) {
// 通知可能存在的子View或drawable觸摸點發生了移動。
drawableHotspotChanged(x, y);
}
// Be lenient about moving outside of buttons
// 確定觸摸點在范圍內
if (!pointInView(x, y, mTouchSlop)) {
// Outside button
// Remove any future long press/tap checks
// 如果移出了這個范圍,首先第4行調用removeTapCall():
removeTapCallback();
removeLongPressCallback();
// 如果pressed標志位為1,那么就取消消息隊列中長按觸發消息,
// 同時去除pressed標志位。
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
}
break;
}
return true;
}
return false;
}// 總結一下,只要觸摸點移動出了當前view,那么所有的點擊、長按事件都不會觸發,
// 但是只要移動還在view+slot范圍內,那么點擊長按事件還是會被觸發的。