一、 摘要
介紹Android中View的事件分發流程,以及對事件的消費和攔截。本文基於Android 8.0(Oreo),即API 26。
二、 View的事件
View有四種基本事件,它們位於MotionEvent中:
- ACTION_DOWN:按壓動作開始的標誌,事件中包含這個初始位置。
- ACTION_UP:按壓結束的標誌,事件中包含這個結束位置。
- ACTION_MOVE:按壓鬆開之前的狀態,事件中包含當前運動位置。
- ACTION_CANCEL:手勢取消了,你應該類比ACTION_UP來處理。
當我們在View上進行交互時,首先硬件層屏幕傳感器捕獲這些信息,然後通過很複雜的流程傳遞到Android應用層,即傳到我們的Activity中,以事件的形式向下分發到各層的View中進行處理。
三、 分發涉及的三個核心方法
1. 概述
View的事件分發流程涉及到三個核心方法:dispatchTouchEvent()、onTouchEvent()和onInterceptTouchEvent(),這三個方法將事件在Activity、Window、DecorView、ViewGroup、View之間傳遞。
通過前兩章(《Android中View的繪製流程》、《Android中View的異步消息》)的學習,我們知道了Window、ViewRootImpl、DecorView、ViewGroup、View之間的關係,在源碼中,Window只有唯一實現類——PhoneWindow:
/**
* <p>The only existing implementation of this abstract class is
* android.view.PhoneWindow, which you should instantiate when needing a
* Window.
*/
public abstract class Window {...}
根據這些知識,我們能夠更快地理解事件分發流程。
接下來我們先介紹這三個方法。
- dispatchTouchEvent()存在於Activity、ViewGroup、View中;
- onTouchEvent()也存在於Activity、ViewGroup、View中;
- onInterceptTouchEvent()僅存在於ViewGroup中。
即:
組件 \ 方法 | dispatchTouchEvent | onTouchEvent | onInterceptTouchEvent |
---|---|---|---|
Activity | YES | YES | |
View | YES | YES | |
ViewGroup | YES | YES | YES |
從字面意思上看,dispatchTouchEvent和分發觸摸事件有關,onTouchEvent和執行觸摸事件有關,onInterceptTouchEvent和攔截觸摸事件有關。
2. Activity中
2.1. dispatchTouchEvent()
/**
* 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) {...}
- 用於處理觸屏事件。
- 你可以重寫這個方法來攔截所有的觸屏事件,不讓他們分發到Window。
- 通常情況下你應該調用這裏的具體實現去處理觸屏事件。
- 如果事件被消費了,返回true。
2.2. onTouchEvent()
/**
* Called when a touch screen event was not handled by any of the views
* under it. This is most useful to process touch events that happen
* outside of your window bounds, where there is no view to receive it.
*
* @param event The touch screen event being processed.
*
* @return Return true if you have consumed the event, false if you haven't.
* The default implementation always returns false.
*/
public boolean onTouchEvent(MotionEvent event) {...}
- 當一個觸屏事件沒有被這個Activity下的任何View處理時,調用該方法。
- 該方法最大的用處是去處理Window邊界以外,沒有View去響應的觸屏事件。
- 如果事件被消費了,返回true。默認返回false。
3. View中
3.1. 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) {...}
- 將觸屏事件向下傳遞到目標視圖,如果當前視圖就是目標,則傳遞到當前視圖。
- 如果事件被處理了,返回true。
3.2. 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) {...}
- 該方法用於處理觸屏事件。
- 如果想用這個方法來監聽點擊動作,建議實現並調用performClick()。這將確保系統行爲一致性,包括:遵守點擊聲音首選項、分發OnClickListener、處理ACTION_CLICK。
- 如果事件被處理了,返回true。
4. ViewGroup中
4.1. dispatchTouchEvent()
重寫了View中的實現。
4.2. onTouchEvent()
繼承View中的方法。
4.3. 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) {...}
- 用於攔截所有的觸屏事件。
- 這使你可以在事件被分發到子視圖時進行監聽,並且在任何時候把控當前手勢。
- 使用時需要當心,因爲它和onTouchEvent()的交互相當複雜,你得以正確的方式來實現這個方法。
- 按這個順序接收事件:(1)接收down事件。(2)既可以用這個ViewGroup的子視圖,也可以用onTouchEvent()這個方法來處理down事件,這意味着你應該實現onTouchEvent()這個方法並返回true,這樣你將看到手勢的剩餘部分(不要用父視圖來處理它)。同樣,通過在onTouchEvent()中返回true,你就不會在onInterceptTouchEvent()中收到任何後續事件,並且所有的觸摸處理只能在onTouchEvent()中正常進行。(3)只要你從這返回false,接下來的每個事件(直到幷包括最終的up事件)都將首先傳遞到這裏,然後傳遞給目標的onTouchEvent()。(4)如果你從這返回true,你將接收不到以下事件:目標視圖會接收相同的事件但是帶着ACTION_CANCEL動作,所有其他事件將被傳遞到onTouchEvent()方法,不再出現在這裏。
- 返回true來攔截來自子視圖的事件,通過onTouchEvent()來分發它們。當前目標將接收一個ACTION_CANCEL事件,並且此處不會再傳遞更多的消息。
四、 事件分發流程
看完了三個核心方法的註釋,被一大堆布爾返回值搞懵了,那麼我們從方法調用棧下手,分析事件分發的具體流程,分析過程中,我們除了要關注向下傳遞的事件,還要關注向上傳遞的返回值,這比一般的方法調用要複雜一些。
在開始介紹流程前,還得搞明白兩個術語:消費和攔截。
1. 什麼是消費
事件被消費,即事件被處理,也就是onTouchEvent()這個方法中的執行情況,因爲Activity、ViewGroup和View中都有onTouchEvent(),所以我們將在它們三個中分別介紹消費的情況。
2. 什麼是攔截
攔截,顧名思義,截斷事件的傳遞過程,當事件被攔截後,無法再向下分發,由於攔截的方法onInterceptTouchEvent()僅存於ViewGroup中,因此我們只會在ViewGroup中分析攔截過程。
3. Activity中的流程
/**
* 分發
*/
public boolean dispatchTouchEvent(MotionEvent ev) {
// 事件開始的標誌:ACTION_DOWN
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
// 你可以重寫這個方法,來得知用戶用什麼方式進行的交互
onUserInteraction();
}
// 將事件分發給Window,如果它消費了,此處也就返回true表示消費了
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
// Window沒消費這個事件的話,Activity就自己來處理,並返回消費情況
return onTouchEvent(ev);
}
/**
* 消費
*/
public boolean onTouchEvent(MotionEvent event) {
// 如果需要關閉Window,即結束Activity,就結束,並返回true表示消費了
if (mWindow.shouldCloseOnTouch(this, event)) {
finish();
return true;
}
return false;
}
/**
* 位於Window類中的shouldCloseOnTouch()
* 主要是根據事件是否出界來判斷是否需要關閉
*/
public boolean shouldCloseOnTouch(Context context, MotionEvent event) {
final boolean isOutside =
event.getAction() == MotionEvent.ACTION_DOWN && isOutOfBounds(context, event)
|| event.getAction() == MotionEvent.ACTION_OUTSIDE;
if (mCloseOnTouchOutside && peekDecorView() != null && isOutside) {
return true;
}
return false;
}
Activity將事件分發到了Window中,而Window唯一實現類是PhoneWindow,我們直接去PhoneWindow中看此處方法:
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
PhoneWindow將事件分發給了DecorView:
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
DecorView將事件分發給了父類,我們知道DecorView是繼承ViewGroup的,因此這裏又將事件分發到了ViewGroup中。
由此可得:
- Activity中,事件被分發到ViewGroup,並返回消費結果。
- 如果ViewGroup返回的消費結果是false,則由Activity自己消費並返回結果。
4. ViewGroup中的流程
/**
* 分發
*/
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
// ...
// 事件是否被消費
boolean handled = false;
// ...
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);
// 此處會將mFirstTouchTarget置空
resetTouchState();
}
// 事件是否被攔截
// Check for interception.
final boolean intercepted;
// ACTION_DOWN是事件開始標誌,因此在ACTION_DOWN情況下判斷攔截
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 (!canceled && !intercepted) {
// ...
// 遍歷子View,並尋找事件座標在界限內的最上層一個子View來分發
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);
// ...
// 根據子View分發
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// ...
// 此處對mFirstTouchTarget實例化
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
// ...
}
// ...
}
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
// 根據子View分發
// 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;
// 循環對子View進行分發,不包括剛纔已經分發過的那個
while (target != null) {
final TouchTarget next = target.next;
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
// 根據子View分發
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
// ...
}
predecessor = target;
target = next;
}
}
if (canceled
|| actionMasked == MotionEvent.ACTION_UP
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
// 此處會將mFirstTouchTarget置空
resetTouchState();
}
// ...
return handled;
}
/**
* 攔截
*/
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;
}
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
// ...
if (child == null) {
// 沒有子View的話,調用父類(即View)的分發方法,並將結果作爲消費結果返回
handled = super.dispatchTouchEvent(transformedEvent);
} else {
// 有子View的話,調用子View的分發方法,並將結果作爲消費結果返回
handled = child.dispatchTouchEvent(transformedEvent);
}
// ...
return handled;
}
/**
* 位於View類中的dispatchTouchEvent()
* 由於ViewGroup沒有重寫onTouchEvent(),因此實際上消費的邏輯還是使用的View的消費邏輯
*/
public boolean dispatchTouchEvent(MotionEvent event) {
// ...
// 消費的結果
boolean result = false;
// ...
if (!result && onTouchEvent(event)) {
result = true;
}
// ...
return result;
}
/**
* 在子View中遍歷到目標,則加到鏈表頭部,並且將mFirstTouchTarget實例化
*/
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
整理一下整個過程:
- Activity將事件分發到DecorView(本身也是ViewGroup)的dispatchTouchEvent()。
- ViewGroup先判斷事件攔截onInterceptTouchEvent(),如果不攔截,找到目標子View(ViewGroup或者View對象)進行分發,並返回消費結果。
- 如果攔截了,則不再向下分發,而是由ViewGroup自己消費,並返回結果。
- 可能有讀者沒看明白爲什麼不攔截最後調用的是super.dispatchTouchEvent(),在dispatchTouchEvent()中有兩處調用resetTouchState()來將mFirstTouchTarget置空,因此每次進入dispatchTouchEvent()時,mFirstTouchTarget都爲null,只有當不攔截時,纔會進入循環體去找到目標子View,並且將mFirstTouchTarget實例化。
5. View中的流程
/**
* 分發
*/
public boolean dispatchTouchEvent(MotionEvent event) {
// ...
// 消費的結果
boolean result = false;
// ...
if (!result && onTouchEvent(event)) {
result = true;
}
// ...
return result;
}
/**
* 消費
*/
public boolean onTouchEvent(MotionEvent event) {
// ...
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
// ...
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
// ...
case MotionEvent.ACTION_DOWN:
// ...
case MotionEvent.ACTION_CANCEL:
// ...
case MotionEvent.ACTION_MOVE:
// ...
}
return true;
}
return false;
}
/**
* 指示此視圖可在懸停或長按下時顯示工具提示。
* <p>Indicates this view can display a tooltip on hover or long press.</p>
* {@hide}
*/
static final int TOOLTIP = 0x40000000;
View的情況比較簡單,很容易理解:
- View作爲基類不能再向下分發了,只能消費。
- 如果當前View可點擊,就處理事件,並返回true作爲消費結果。