事件分發(fā)的重要性我就不多說了,我們先從簡到難青瀑。
先看View
的Touch
事件分發(fā),我自定義一個View
衣撬,重寫OnTouchEvent
函數(shù),然后分別設(shè)置OnTouchListener
和OnClick
:
ACTION_DOWN = 0 ACTION_UP=1 ACTION_MOVE=2
我們我們按下這個View
點擊一下:
可以發(fā)現(xiàn)執(zhí)行的順序是:
OnTouchListener.DOWN -> OnTouchEvent.DOWN -> OnTouchListener.MOVE -> OnTouchEvent.MOVE -> OnTouchListener.UP-> OnTouchEvent.UP-> OnClickListener
從這我們就可以猜想執(zhí)行的優(yōu)先級為
OnTouchListener > onTouchEvent > onClick
接下來我們驗證這個猜想终息,
我們把OnTouchListener
的onTouch
返回值改為true
我在點擊一下夺巩,這里大膽猜想一下
onTouchEvent
和onClick
不會執(zhí)行了,看看執(zhí)行的順序
這時候執(zhí)行的順序如下:
OnTouchListener.DOWN ->OnTouchListener.MOVE-> OnTouchListener.UP
這里驗證了我的猜想周崭,可以得到如下結(jié)論
View
的Touch
事件分發(fā)柳譬,OnToucherListener
如果返回true
的話,就說明把事件從OnToucherListener
這里攔截了续镇,后續(xù)的onTouchEvent
和onClick
就收不到事件了美澳。
接下來我們把OnTouchListener
的onTouch
返回值改為false
,讓它不攔截事件,把onTouchEvent
返回值改為true
我們點擊一下,猜想是
OnTouchListener
和onTouchEvent
能夠接收到事件摸航,onClick
將不會觸發(fā)
和我們想的一致制跟,這時候執(zhí)行順序變?yōu)?
OnTouchListener.DOWN ->OnTouchEvent.DOWN-> OnTouchListener.MOVE -> OnTouchEvent.MOVE->OnTouchListener.UP ->OnTouchEvent.UP
這里我們就可能得到結(jié)論
View
的Touch
事件分發(fā),如果OnToucherListener
返回false
酱虎,onTouchEvent
返回true
凫岖,就說明把事件從onTouchEvent
這里攔截了,onClick
就不會觸發(fā)逢净。
通過上面兩個結(jié)論我們驗證了我們的優(yōu)先級猜想
View
的Touch
事件分發(fā)哥放,執(zhí)行的優(yōu)先級為OnTouchListener > onTouchEvent > onClick
,如果前兩個任意一個地方返回true
爹土,那么后續(xù)將不會收到事件甥雕。
接下來我們從源碼的角度分析,首先我們需要知道,你點擊或者或者觸摸任何一個View
都會調(diào)用 dispatchTouchEvent()
函數(shù)胀茵,我們就從這里開始分析源碼:
/**
* 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
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);
}
// 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.
if (actionMasked == MotionEvent.ACTION_UP ||
actionMasked == MotionEvent.ACTION_CANCEL ||
(actionMasked == MotionEvent.ACTION_DOWN && !result)) {
stopNestedScroll();
}
return result;
}
我們先要知道ListenerInfo
這個是做什么的社露?
static class ListenerInfo {
/**
* Listener used to dispatch focus change events.
* This field should be made private, so it is hidden from the SDK.
* {@hide}
*/
protected OnFocusChangeListener mOnFocusChangeListener;
/**
* Listeners for layout change events.
*/
private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
protected OnScrollChangeListener mOnScrollChangeListener;
/**
* Listeners for attach events.
*/
private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
/**
* Listener used to dispatch click events.
* This field should be made private, so it is hidden from the SDK.
* {@hide}
*/
public OnClickListener mOnClickListener;
/**
* Listener used to dispatch long click events.
* This field should be made private, so it is hidden from the SDK.
* {@hide}
*/
protected OnLongClickListener mOnLongClickListener;
/**
* Listener used to dispatch context click events. This field should be made private, so it
* is hidden from the SDK.
* {@hide}
*/
protected OnContextClickListener mOnContextClickListener;
/**
* Listener used to build the context menu.
* This field should be made private, so it is hidden from the SDK.
* {@hide}
*/
protected OnCreateContextMenuListener mOnCreateContextMenuListener;
private OnKeyListener mOnKeyListener;
private OnTouchListener mOnTouchListener;
private OnHoverListener mOnHoverListener;
private OnGenericMotionListener mOnGenericMotionListener;
private OnDragListener mOnDragListener;
private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
}
這是一個view
所有事件的集合類。接下來進入這段代碼,
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;
}
從這段代碼我們就可以知道如果mOnTouchListener !=null
并且當(dāng)前view
的是enable=true
就會執(zhí)行li.mOnTouchListener.onTouch(this, event)
,執(zhí)行li.mOnTouchListener.onTouch(this, event)
返回的false
的話就會執(zhí)行onTouchEvent(event)
琼娘。
從這我們就可以知道OnTouchListener
的優(yōu)先級大于onTouchEvent
峭弟。接著我們點擊onTouchEvent
進入
public boolean onTouchEvent(MotionEvent event) {
//......代碼太長 省略
switch (action) {
case MotionEvent.ACTION_UP:
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.
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.
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) {
// 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();
}
}
}
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
if (prepressed) {
postDelayed(mUnsetPressedState,
ViewConfiguration.getPressedStateDuration());
} else if (!post(mUnsetPressedState)) {
// If the post failed, unpress right now
mUnsetPressedState.run();
}
removeTapCallback();
}
mIgnoreNextUpEvent = false;
break;
case MotionEvent.ACTION_DOWN:
mHasPerformedLongPress = false;
if (performButtonActionOnTouchDown(event)) {
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;
case MotionEvent.ACTION_CANCEL:
setPressed(false);
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
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;
}
可以看到附鸽,我們在MotionEvent.ACTION_UP
事件里面,經(jīng)過一系列的判斷瞒瘸,然后進入到了performClick()
這個函數(shù)
/**
* Call this view's OnClickListener, if it is defined. Performs all normal
* actions associated with clicking: reporting accessibility event, playing
* a sound, etc.
*
* @return True there was an assigned OnClickListener that was called, false
* otherwise is returned.
*/
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;
}
這個函數(shù)很明顯的就知道是執(zhí)行onClick
,從這就可以得到如下結(jié)論
onClick
事件是在onTouchEvent
的MotionEvent.ACTION_UP
事件通過performClick()->li.mOnClickListener.onClick(this)
觸發(fā)的坷备。
到這里我們就驗證了我們剛才的優(yōu)先級的結(jié)論。當(dāng)然在onTouchEvent(MotionEvent event
源碼中情臭,我們在MotionEvent.ACTION_DOWN
里面可以看到長按事件
case MotionEvent.ACTION_DOWN:
//...
checkForLongClick(0, x, y);
break;
//檢測長按事件
private void checkForLongClick(int delayOffset, float x, float y) {
if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
mHasPerformedLongPress = false;
if (mPendingCheckForLongPress == null) {
mPendingCheckForLongPress = new CheckForLongPress();
}
mPendingCheckForLongPress.setAnchor(x, y);
mPendingCheckForLongPress.rememberWindowAttachCount();
postDelayed(mPendingCheckForLongPress,
ViewConfiguration.getLongPressTimeout() - delayOffset);
}
}
private final class CheckForLongPress implements Runnable {
private int mOriginalWindowAttachCount;
private float mX;
private float mY;
@Override
public void run() {
if (isPressed() && (mParent != null)
&& mOriginalWindowAttachCount == mWindowAttachCount) {
//觸發(fā)長按事件
if (performLongClick(mX, mY)) {
mHasPerformedLongPress = true;
}
}
}
public void setAnchor(float x, float y) {
mX = x;
mY = y;
}
public void rememberWindowAttachCount() {
mOriginalWindowAttachCount = mWindowAttachCount;
}
}
public boolean performLongClick(float x, float y) {
mLongClickX = x;
mLongClickY = y;
final boolean handled = performLongClick();
mLongClickX = Float.NaN;
mLongClickY = Float.NaN;
return handled;
}
public boolean performLongClick() {
return performLongClickInternal(mLongClickX, mLongClickY);
}
private boolean performLongClickInternal(float x, float y) {
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
boolean handled = false;
final ListenerInfo li = mListenerInfo;
if (li != null && li.mOnLongClickListener != null) {
handled = li.mOnLongClickListener.onLongClick(View.this);
}
if (!handled) {
final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
}
if (handled) {
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
}
return handled;
}
從這段代碼我們又可以得到如下結(jié)論
View
的OnLongClickListener
是在onTouchEvent
的MotionEvent.ACTION_DOWN
事件通過checkForLongClick() ->performLongClick(mX, mY)->performLongClick() ->performLongClickInternal(mLongClickX, mLongClickY) ->li.mOnLongClickListener.onLongClick(View.this)
的執(zhí)行順序觸發(fā)的省撑。
這樣View
的OnTouch
事件分發(fā)機制就分析得差不多,具體的判斷細節(jié)等還是需要自己查看源碼俯在。
參考鏈接:
http://www.reibang.com/p/98d1895c409d
http://www.reibang.com/p/e99b5e8bd67b