android事件分发机制
android的事件分发机制可以分为3类:activity事件分发,viewGruop事件分发及子view事件分发。事件分发相关的三个方法:
- dispatchTouchEvent()
- onIterceptTouchEvent()
- onTouchEvent()
其中onIterceptTouchEvent()方法仅存在于viewGroup中。下面通过源码的形式具体分析这三类是如何进行事件分发的
1、activity事件分发
进入Activity类中,找到dispatchTouchEvent()方法,源码如下
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//1
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {//2
return true;
}
//3
return onTouchEvent(ev);
}
其中用户首先会触发的是down事件,1处的方法是根据用户的需求进行重写,源码中是个空方法。再看2处。其中getWindow()就是我们的Window类对象,而我们的Window的唯一实现类是PhoneWindow,进入PhoneWindow的该方法
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
//1
return mDecor.superDispatchTouchEvent(event);
}
1处注释,其中mDecor为DecorView对象,再次点击进入该方法
public boolean superDispatchTouchEvent(MotionEvent event) {
//1
return super.dispatchTouchEvent(event);
}
都知道,DecorView是继承至FrameLayout的,FrameLayout是ViewGroup的子类,所以点击1处方法会进入ViewGroup的dispatchTouchEvent()。回到Activity的dispatchTouchEvent方法,如果getWindow().superDispatchTouchEvent(ev)返回true,该方法直接返回true。
总结一下activity的事件分发:
也就是说事件分发是从Activity的dispatchTouchEvent()开始,往ViewGroup的dispatchTouchEvent()传递。如果返回true。说明事件被viewgroup消费,事件结束。如果没有被消费,则会交给Activity的onTouchEvent()处理。
2、ViewGroup事件分发
进入ViewGruop类中dispatchTouchEvent(...)方法,源码如下:
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
//注释1
cancelAndClearTouchTargets(ev);
//注释2
resetTouchState();
}
// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
//注释3
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
//注释4
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;
}
...
}
该方法内容很多,先分析一部分。注释1处表示如果我们的ACTION_DOWN事件是一个新的开始,就使我们的mFirstTargetEvent = null;再看第2处注释,如下源码:
private void resetTouchState() {
clearTouchTargets();
resetCancelNextUpFlag(this);
//1
mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
mNestedScrollAxes = SCROLL_AXIS_NONE;
}
该方法将我们的mGroupFlags的标志位进行了清除操作。回到上面的方法,会进入我们的down事件,看注释3,因为mGroupFlags在前面已经进行了清除,所以这个参数在,全新的down事件disallowIntercept 一定为false,并且子view可以调用requestDisallowInterceptTouchEvent()来拦截父view除down事件以外的事件(原因:down事件中会对mGroupFlags重新赋值,disallowIntercept 一定为false,在down事件中调用requestDisallowInterceptTouchEvent()方法没有任何作用)。然后会进入注释4,进入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;
}
拦截事件默认返回false,也就是说默认不拦截,所以intercepted 默认值为false。所以会执行if里面的内容。源码如下:
public boolean dispatchTouchEvent(MotionEvent ev) {
...
if (!canceled && !intercepted) {
...
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
...
final int childrenCount = mChildrenCount;
if (newTouchTarget == null && childrenCount != 0) {
...
for (int i = childrenCount - 1; i >= 0; i--) {
...
if (!canViewReceivePointerEvents(child)//注释1
|| !isTransformedTouchPointInView(x, y, child,null)) //注释2{
ev.setTargetAccessibilityFocus(false);
continue;
}
...
//注释3
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
...
//注释4
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();
}
...
}
}
// 注释5
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
TouchTarget predecessor = null;
TouchTarget target = mFirstTouchTarget;
while (target != null) {
final TouchTarget next = target.next;
// 注释6
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
//注释7
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;
}
}
//注释8.
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的子view个数不为空,那么它会倒序遍历子view,会调用注释1和注释2的方法,这两个方法的意思是如果当前子view不可见或者是在执行动画或者不在view的触摸区域内,该view就不处理事件。加入两个条件都不成立,继续走到注释4,该方法源码如下:
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
// Canceling motions is a special case. We don't need to perform any transformations
// or filtering. The important part is the action, not the contents.
final int oldAction = event.getAction();
if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
event.setAction(MotionEvent.ACTION_CANCEL);
if (child == null) {
handled = super.dispatchTouchEvent(event);//1
} else {
handled = child.dispatchTouchEvent(event);//2
}
event.setAction(oldAction);
return handled;
}
可以看到当子view为空时,说明已经没有了子view,由于这里的view不为空,那么会调用2处方法,会将事件传递给子view的dispatchTouchEvent(...)。如果handled 返回true,说明事件分发成功,会走到注释4,看源码:
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
这里会将mFirstTouchTarget 赋值。如果没有找到可以消耗事件的子view,那么handled就会返回false,则mFirstTouchTarget 为空。会进入上面的注释5。下面分析注释5处的源码:继续回调用dispatchTransformedTouchEvent()方法,并且此时子view传递为null,再回到这个方法中,会执行super.dispatchTouchEvent()方法,交给我们ViewGroup的onTouchEvent()方法。如果找到了down事件中可以处理事件的子view,那么后续将会交给子view处理。回到ViewGroup的dispatchTouchEvent()方法,看注释6,会判断当前down事件是否被消耗,如果是则返回handlered为true,否则会执行子view的其他事件,比如move,up事件等。
总结一下:
(1)如果viewGroup拦截事件或者子view没有消费事件,那么会交给viewGroup的onTouchEvent继续处理事件。如果有子view消耗了down事件,那么会交给子view继续处理后续事件(注释7)。(2)如果viewGroup对事件进行了拦截,那么执行完down事件后mFirstTouchTarget为空,所以进行到其他事件时,将不会再进行拦截,即不会调用onIterceptTouchEvent()事件。(参考如下源码)。(3)另外子view可以调用requestDisallowInterceptTouchEvent()方法拦截除down事件以外的viewGroup其他事件。(4)viewGroup的dispatchTouchEvent()方法是真正的执行分发操作,而view的该方法不会进行分发操作,而是交给自己的onTouchEvent()处理(5)dispatchTouchEvent()方法不处理事件,真正处理事件的是onTouchEvent()事件
public boolean dispatchTouchEvent(MotionEvent ev) {
...
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;
}
}
...
}
分发伪代码截图如下:
3、view的事件处理
首先从dispatchTouchEvent()方法看起,源码如下:
public boolean dispatchTouchEvent(MotionEvent event) {
// If the event should be handled by accessibility focus first.
...
if (onFilterTouchEventForSecurity(event)) {
//...
//1
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
//2
if (!result && onTouchEvent(event)) {
result = true;
}
}
...
return result;
}
看1处的判断条件,如果我们设置了onTouch()事件的监听器,即设置了onTouchListener方法,则li!=null,并且控件默认情况下是ENABLED的,所以会触发onTouch()方法,那么导致onTouchEvent()事件不会调用,并且后续的onClick与onLongClick更不会执行。说明onTouch()事件的优先级高于onTouchEvent()事件。否则进入onTouchEvent()事件,源码如下:
public boolean onTouchEvent(MotionEvent event) {
...
//1
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
if ((viewFlags & ENABLED_MASK) == DISABLED) {//2
...
return clickable;
}
...
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
...
if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
// This is a tap, so remove the longpress check
removeLongPressCallback();
...
}
...
break;
case MotionEvent.ACTION_DOWN:
...
mHasPerformedLongPress = false;//3
if (!clickable) {
checkForLongClick(0, x, y);
break;
}
if (performButtonActionOnTouchDown(event)) {
break;
}
// Walk up the hierarchy to determine if we're inside a scrolling container.
//4
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);
//5
checkForLongClick(0, x, y);
}
break;
case MotionEvent.ACTION_CANCEL:
...
break;
case MotionEvent.ACTION_MOVE:
...
break;
}
return true;
}
return false;
}
注释1处说明只要是click或onLongClick事件中的一种那么clickable就为true,注释2处说明,无论当前控件是不是DISABLED状态,都不会影响点击事件,只是控件没有相应而已。注释3处变量含义是的当前view是否处理了长按事件。注释4处的含义是判断当前view是否处于某个可滑动的容器中,如果条件成立会调用postDelay()延迟方法,延时时间为100ms,来检测我们的长按事件;如果不处于某个容器,最总也会调用postDelay()延迟方法检测长按事件,延迟时间为500ms。也就是说在Down事件中会检测我们的长按事件。如果检测出则注释3处的返回值为false,则会在up事件中将长按事件回调移除。如果在500ms结束之前他会做哪些操作呢?首先会进入注释5处方法:
private void checkForLongClick(int delayOffset, float x, float y) {
if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
mHasPerformedLongPress = false;
if (mPendingCheckForLongPress == null) {
//1
mPendingCheckForLongPress = new CheckForLongPress();
}
mPendingCheckForLongPress.setAnchor(x, y);
mPendingCheckForLongPress.rememberWindowAttachCount();
mPendingCheckForLongPress.rememberPressedState(); postDelayed(mPendingCheckForLongPress,
ViewConfiguration.getLongPressTimeout() - delayOffset);
}
}
继续进入1处CheckForLongPress的run()方法:
public void run() {
if ((mOriginalPressedState == isPressed()) && (mParent != null)
&& mOriginalWindowAttachCount == mWindowAttachCount) {
if (performLongClick(mX, mY)) {
mHasPerformedLongPress = true;
}
}
}
会调用performLongClick(),继续进入该方法
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);
}
...
return handled;
}
会执行onLongClick()方法,也就是说如果view设置了onLongListener事件,那么如果该事件返回为true,那么mHasPerformedLongPress就为true,表示长按事件被执行。再回到view的onTouchEvent方法的up事件中:
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;
}
}
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
...
//1
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) {
//2
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
performClickInternal();
}
}
}
...
break;
case MotionEvent.ACTION_DOWN:
...
break;
case MotionEvent.ACTION_CANCEL:
...
break;
case MotionEvent.ACTION_MOVE:
...
break;
}
return true;
}
return false;
}
可以看出只有mHasPerformedLongPressed为false才会进入2处方法,也就是说如果在500ms内mHasPerformedLongPressed肯定为false,就会触发onClick事件,如果超过500ms那么如果onLongClick事件返回true,就不会传递给onClick事件。如果onLongClick事件返回false,呢么依然会执行onClick事件。所以onLongClick的优先级高于onClick事件,并且onLongClick事件和onClick事件可以同时执行回调。
至此事件分发流程结束,下面附上几张张图方便大家理解: