安卓事件分发机制一直是困扰大家的一个难点,最近项目不忙抽出一周的时间好好研究了一下。首先上图一目了然,这张图是自己写了activity,ViewGroup,view,打log试出来的,和网上的的总结也是一样的结果。
我们可以总结一个简单的规律就是,true自己消费,false传给上一级。
事件分发的源码分析
1.Activity对事件的分发
我们主要是分析MotionEvent,事件都是由外向里传递,所以是从Activity的dispatchTouchEvent来进行事件分发的。
那么我们就从Activity的dispatchTouchEvent开始分析
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
a.首先判断是否是Action_Down事件,如果是:调用onUserInteraction();【注释中解释此方法是帮助Activity智能管理状态栏,帮助Activity在合适的时间取消通知】
b.判断window的superDispatchTouchEvent(ev),如果返回true,那么此事件就结束了,自己消费,如果返回false,那么证明没人处理,就直接return onTouchEvent(ev);
接下来我们主要看这个方法
getWindow().superDispatchTouchEvent(ev)
点进去看,这个方法和类都是抽象的,所以要找他的实现类,通过注解我们了解到PhoneWindow是Window的唯一实现类。
phoneWindow:
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
a.通过代码可以看出,PhoneWindow调用的是DecorView的superDispatchTouchEvent(event)
decorView
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
a.decorView继承FrameLayout,所以调用的是FrameLayout的dispatchTouchEvent,FrameLayout没有重写此方法,就直接调用ViewGroup的dispatchTouchEvent。
2.ViewGroup对事件的分发过程
ViewGroup的dispatchTouchEvent比较长,我们分开来解读,省略不必要的代码。
// Check for interception.
final boolean intercepted;
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;
}
a. 在down事件和mFirstTouchTarget != null事件会拦截当前事件。 mFirstTouchTarget 在后面的子View处理当前事件的时候会被赋值,也就是说只要子View拦截当前事件,mFirstTouchTarget != null就成立,也就是说如果是子View处理了事件,依然会走onInterceptTouchEvent。
其中onInterceptTouchEvent默认是不拦截的返回的是false
b. 如果ViewGroup处理当前事件的话,mFirstTouchTarget != null就不成立,如果是up和move事件,就不会走onInterceptTouchEvent。
c. 这里有个特殊情况,那就是这个disallowIntercept ,其中FLAG_DISALLOW_INTERCEPT是在子View中设置的,通过我们自己调用requestDisallowInterceptTouchEvent方法进行设置,一旦设置了那么ViewGroup就无法拦截除down以外的事件,可以用来解决滑动冲突。
d.为什么说是除了down以外的事件,因为如果是down事件的话,话重新设置状态。下面的代码可以解释:
ViewGroup的dispatchTouchEvent:
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();
}
接着咱们往下走
ViewGroup的dispatchTouchEvent:
A: 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);
// If there is a view that has accessibility focus we want it
// to get the event first and if not handled we will perform a
// normal dispatch. We may do a double iteration but this is
// safer given the timeframe.
B:
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
C:
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
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;
}
D:
resetCancelNextUpFlag(child);
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
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();
E:
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();
}
- A :遍历所有子View,找到可以处理当前的事件的view。
- B :判断可以访问焦点的子view是否为空
- C :判断child可不可以接受这个触摸事件,(当view可见,或者animation不为空的时候表示可以接受)或者触摸事件发生的位置是否在view范围内。
- D :到此调用dispatchTransformedTouchEvent,此方法中当child不为空就直接调用子view的dispatchTouchEvent(从而完成了一轮事件分发)
viewGroup 的dispatchTransformedTouchEvent:
if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
event.setAction(MotionEvent.ACTION_CANCEL);
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
event.setAction(oldAction);
return handled;
- E:如果子View的dispatchTouchEvent返回true,就会调用停止for循环,如果返回false就把事件传给下一个继续判断(如果有下一个),mFirstTouchTarget会在addTouchTarget中进行赋值。
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
如果遍历所有子元素都没有处理这个事件,那么mFirstTouchTarget就为null,就会走下面下面这段代码:
viewGroup 的dispatchTouchEvent
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
}
这个方法也是调用的dispatchTransformedTouchEvent,其中第三个参数传入的是null,即child为null,那么就会走到View的dispatchTouchEvent方法。
3.View的对事件的处理
对于View的dispatchTouchEvent事件就比较简单了,因为没有向下传递了。
View的DispatchTouchEvent
···省略无关代码
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;
}
···省略无关代码
return result;
可以看出来是先判断是否有设置OnTouchListener ,并且OnTouchListener 的onTouch事件是否返回true,如果是,那么result就是true,那么!result就为false,&&后面的就直接不走了,这就能证明OnTouchListener 优先级高于OnTouchEvent。
接下来我们来看OnTouchEvent
A:
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;
}
B:
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
- A:即使我们设置了View不可见,当前的View也依然会处理这个事件
- B:如果设置了代理,那就会调用代理的onTouchEvent。
接着往下走就会注意到有一个方法:performClick();
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
···省略部分无关代码
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();
}
}
只要view的clickable 即CLICKABLE和LONG_CLICKABLE其中有一个为true,就会消耗这个事件,那么onTouchEvent就返回true,接着就会触发 performClick()方法。如果我们设置了mOnClickListener,那么就会在performClick()方法中调用mOnClickListener.onClick(this);方法,来处理此次事件。
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;
}
······
return result;
}
到这里我们就把事件分发的源码分析完了。只要耐下心来看,研究都可以学会。