View 的事件分发机制
Posted Young_xiaoT
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了View 的事件分发机制相关的知识,希望对你有一定的参考价值。
View 的事件分发机制
点击事件的分发过程由三个重要的方法来完成:dispatchTouchEvent、onInterceptTouchEvent和onTouchEvent。
从一个简单的项目开始,一个Activity中只有一个Button,同时注册onClickListener和onTouchListener 两个事件,onTouch方法里能做的事情比onClick要多一些,比如判断手指按下,抬起,移动等事件。
运行点击按钮:
com.example.youngtr.viewdispatch D/MainActivity: Touch execute , action 0
com.example.youngtr.viewdispatch D/MainActivity: Touch execute , action 1
com.example.youngtr.viewdispatch D/MainActivity: Click execute
根据打印结果,可以看出onTouch优先于onClick执行的,并且onTouch执行了两次,一次是ACTION_DOWN,一次是ACTION_UP。事件传递是 onTouch -> onClick 。
下面把onTouch方法的返回值改为 true ,运行结果如下:
com.example.youngtr.viewdispatch D/MainActivity: Touch execute , action 0
com.example.youngtr.viewdispatch D/MainActivity: Touch execute , action 1
可以发现,onClick方法不再执行,可以理解为 onTouch方法返回true 就认为这个事件被onTouch方法消费掉了,所有不会传递下去。
首先要知道,只要触摸了任何一个控件,就一定会调用该类控件的dispatchTouchEvent方法,先看一下 View 中 dispatchTouchEvent 方法的 源码:
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))
//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;
重点看这一段:
if (onFilterTouchEventForSecurity(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;
第一个和第二个条件,也可以在源码中找到赋值的结果:
public void setOnTouchListener(OnTouchListener l)
getListenerInfo().mOnTouchListener = l;
其中 ListenerInfo 是一个 静态内部类,其中的成员变量均为接口,getListenerInfo()方法将会实例化该成员类
ListenerInfo getListenerInfo()
if (mListenerInfo != null)
return mListenerInfo;
mListenerInfo = new ListenerInfo();
return mListenerInfo;
这里,注册了touch事件,说明 mListenerInfo 和 mTouchListener 一定不为 null 。
第三个条件,(mViewFlags & ENABLED_MASK) == ENABLED 判断当前的控件是否为 enable,按钮默认都是 enable 的,因此这个条件恒定为 true。
第四个条件比较关键,li.mOnTouchListener.onTouch(this, event),其实就是去回调控件注册 touch事件时的 onTouch方法。也就是说,如果我们在onTouch方法里返回true,就会让这三个条件全部成立,整个方法就会返回true。 如果在onTouch方法里返回false,就会再去执行 onTouchEvent(event)方法。
这样可以看出,dispatchTouchEvent 中最先执行的是 onTouch方法,因此 onTouch 肯定要优先于 onClick 执行;如果在 onTouch 方法中返回了 true,就不会再去执行 onTouchEvent 方法,onClick 事件也不会被执行。这里可以看出,onClick的调用一定是在 onTouchEvent(event)方法中的。
下面看一下 onTouchEvent 的源码
public boolean onTouchEvent(MotionEvent event)
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
if ((viewFlags & ENABLED_MASK) == DISABLED)
if (event.getAction() == 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));
if (mTouchDelegate != null)
if (mTouchDelegate.onTouchEvent(event))
return true;
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE))
switch (event.getAction())
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)
// 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();
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);
break;
case MotionEvent.ACTION_CANCEL:
setPressed(false);
removeTapCallback();
removeLongPressCallback();
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;
如果该控件是可以点击就会进入switch判断中去,而如果当前的事件是抬起手指,则会进入到MotionEvent.ACTION_UP这个case当中,经过种种判断之后,会执行 performClick() 方法:
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;
可以看到,只要 mListenerInfo 和 mOnClickListener 不为 null,就会去调用它的 onClick 方法,可以看一下mOnClickListener的赋值:
public void setOnClickListener(@Nullable OnClickListener l)
if (!isClickable())
setClickable(true);
getListenerInfo().mOnClickListener = l;
我们通过调用setOnClickListener方法来给控件注册一个点击事件,就会给mOnClickListener赋值,然后每当控件被点击时,都会在performClick()方法里回调被点击控件的 onClick 方法。
注意
touch事件的层级传递,就是当dispatchTouchEvent在进行事件分发的时候,只有前一个action返回true,才会触发后一个action。
- onTouch 和 onTouchEvent 有什么区别,又该如何使用?
这两个方法都是在View的dispatchTouchEvent中调用,onTouch优先于onTouchEvent执行。如果 onTouch 方法中返回true将事件消费掉,onTouchEvent将不会再执行。
以上是关于View 的事件分发机制的主要内容,如果未能解决你的问题,请参考以下文章
Android6.0 ViewGroup/View 事件分发机制详解