这是对前两篇的总结和补充
1、对于一个根ViewGroup来说,点击事件产生后,首先会传给它的dispatchTouchEvent方法,如果onIterceptTouchEvent方法返回false,不拦截该事件,则执行其子View/ViewGroup的dispatchTouchEvent方法,如果如果onIterceptTouchEvent方法返回true,则表示拦截改事件,则执行其本身的onToucheEvent方法。
public boolean dispatchTouchEvent (MotionEvent ev){
boolean result =false;
if(onInterceptTouchEvent(ev)){
result=onTouchEvent(ev);
}else{
result=child.dispatchTouchEvent(ev);
}
returen result;
}
2、当一个View需要处理事件时,如果设置setOnTouchListener,其onTouch返回false,则onTouchEvent调用,如果onTouch返回true,则onTouchEvent不调用,可以看到setOnTouchListener的优先级 > onTouchEvent > setOnClickListener。
3、事件传递的顺序:Activity -> Window -> View,顶级View接收到传递事件之后,然后一步步分发下去。但如果一个View的onTouchEvent返回false,就会往上调用其父控件的onTouchEvent,依此类推,如果所有的View都不处理该事件,则会将该事件又传递给Activity,即传递给Activity的onTouchEvent方法。
4、如果一个ViewGroup决定拦截,那么这个事件就只能由它来处理,并且onInterceptTouchEvent在调用一次DOWN之后,不再调用,会走ViewGroup的onTouchEvent方法。
5、再父控件不拦截的情况下,无论父控件是否消费事件,点击子控件都会优先把事件交给子控件来消费,只有子控件不消费事件的时候,才会再传递给父控件来消费。这也很好理解,上级有能力做某事,但优先交给下级做,下级做不了,上级才会做。
6、如果View不消耗除了ACTION_DOWN以外的其他事件,那么这个点击事件会消失,此时父元素的onTouchEvent并不会调用,当前View可以收到后续的事件,最终,这些消失的点击事件会传递给Activity。
7、View和ViewGroup不同,ViewGroup有onInteceptTouchEvent方法,只有当onInteceptTouchEvent返回true,拦截掉事件之后,才会调用本身的onTouchEvent方法,而View没有onInteceptTouchEvent方法,会直接调用本身的onTouchEvent方法。
8、View的enable属性不影响onTouchEvent的默认返回值,只要它的clickable或者longCikcable有一个为true,那么它的onTouchEvent就返回true。
9、onClick会发生的前提是当前View是可点击的,并且它收到了down和up的事件。
10、通过requestDisallowInterceptTouchEvent方法,子元素可以干预父元素的事件分发过程,但是无法干预ACTION_DOWN事件,因为在VIewGroup的dispatchTouchEvent中,对ACTION_DOWN做了处理,每次都会重置mGroupFlags值。
Activity对点击事件的分发过程
一个点击事件发生时,最先传递给当前的Activity,由其dispatchTouchEvent派发,流程为:Activity -> Window -> DecorView -> 下面的各个childView。
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
onUserInteraction() 是一个空方法,我们可以在外部复写使用,接着往下,调用Window的superDispatchTouchEvent(ev)方法,如果返回true,代表事件消费掉,则整个事件循环结束,如果返回false,则代表没有消费,就会调用Activity的onTouchEvent方法,证明了结论6。
Window是抽象类,它的实现类为PhoneWindow。
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
调用了DecorView的superDispatchTouchEvent方法。
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
最终,通过super.dispatchTouchEvent(event);调用了ViewGroup的dispatchTouchEvent方法,开启了View的事件传递。
ViewGroup的事件分发流程
点击事件在通过Activity -> Window之后,最终到达顶级View,DecorView中,通过dispatchTouchEvent方法经行派发,如果ViewGroup拦截了事件,即onIntercetTouchEvent返回true,则事件交给ViewGroup本身处理,会调用onTouchEvent方法,如果此刻给ViewGroup设置setOnTouchListener,则优先调用onTouch方法,如果onTouch返回true,则不会调用onTouchEvent方法。
如果ViewGroup不拦截事件,则会传递给其子view,这时子view的dispatchTouchEvent方法被调用,传递过程跟顶级View是一样的,如此循环,直到消费事件为止。
如果事件没有消费,则传递给Activity的onTouchEvent方法。
ViewGroup如何拦截事件?
// 检查intercepted
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);
} else {
intercepted = false;
}
} else {
intercepted = true;
}
首先,当事件类型为ACTION_DOWN或者mFirstTouchTarget!=null时,ViewGroup会判断是否要拦截当前事件,ACTION_DOWN很好理解,mFirstTouchTarget是什么意思,当事件成功交给子控件处理,就是不拦截事件时,mFirstTouchTarget!=null,当事件拦截,mFirstTouchTarget==null,所以,如果ViewGroup拦截事件,在当MOVE和UP事件进来时,所有条件不成立,不会在执行onInterceptTouchEvent方法,验证结论4。
这里面还有一个变量disallowIntercept,这个变量是通过requestDisallowInterceptTouchEvent来设置的,一旦设置之后,ViewGroup就无法拦截除了ACTION_DOWN以外的事件。之所以无法拦截ACTION_DOWN事件,是因为在拦截之前,会把FLAG_DISALLOW_INTERCEPT标记进行重置,这也证实了结论10。
if (actionMasked == MotionEvent.ACTION_DOWN) {
cancelAndClearTouchTargets(ev);
resetTouchState();
}
private void resetTouchState() {
clearTouchTargets();
resetCancelNextUpFlag(this);
mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
mNestedScrollAxes = SCROLL_AXIS_NONE;
}
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
return;
}
if (disallowIntercept) {
mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
} else {
mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
}
if (mParent != null) {
mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
}
}
ViewGroup不拦截事件,将事件分发给childView。
//
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 (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
//子元素是否能接受事件--能否可见,是不是在执行动画
if (!canViewReceivePointerEvents(child)
//点击事件的坐标是否落在子元素内
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
resetCancelNextUpFlag(child);
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
mLastTouchDownTime = ev.getDownTime();
if (preorderedList != null) {
for (int j = 0; j < childrenCount; j++) {
if (children[childIndex] == mChildren[j]) {
mLastTouchDownIndex = j;
break;
}
}
} else {
mLastTouchDownIndex = childIndex;
}
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
ev.setTargetAccessibilityFocus(false);
}
上面的代码逻辑非常清晰,可以看到,dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)这个方法内部,是这样实现的。如果子控件为null就调用View的dispatchTouchEvent方法,如果子控件不为null,就会调用子控件的dispatchTouchEvent派发事件,完成下轮事件分发。
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
如果dispatchTransformedTouchEvent返回true,那么mFirstTouchTarget就会赋值,并且跳出for循环。
//
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
// mFirstTouchTarget 赋值的方法
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
接着走下面
if (mFirstTouchTarget == null) {
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
TouchTarget predecessor = null;
TouchTarget target = mFirstTouchTarget;
while (target != null) {
final TouchTarget next = target.next;
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
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;
}
}
在第一次点击事件时,没给mFirstTouchTarget赋值,有两种情况:第一种,ViewGroup没有子元素,第二种,child不为null时,dispatchTransformedTouchEvent返回false,说明子控件的dispatchTouchEvent中返回false。
到这里我们总结一下,如果dispatchTransformedTouchEvent返回true,mFirstTouchTarget!=null,跳出for循环。如果dispatchTransformedTouchEvent返回false,mFirstTouchTarget==null。注意下面代码,第三个参数为null,就会转到View的dispatchTouchEvent方法。
最终调用ViewGroup本身的onTouchEvent方法,自己处理点击事件,证明了结论4。
if (mFirstTouchTarget == null) {
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
}
单child为null,调用super.dispatchTouchEvent方法,这到了View,View对事件处理比较简单。
public boolean dispatchTouchEvent(MotionEvent event) {
boolean result = false;
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 true;
}
可以看到,首先会判断有没有设置setTouchListener方法,如果onTouch方法返回true,那么onTouchEvent便不会调用,优先级OnTouchListener的优先级高于onTouchEvent.
public boolean onTouchEvent(MotionEvent event) {
...
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == 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)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
}
...
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
(viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
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;
return false;
}
在看OnTouchEvent方法,即使View是DISABLED 不可用状态,但是如果是可点击或者可长按状态,都会返回true,消费事件。
在onTouchEvent的ACTION_UP事件分发时,会调用performClick方法,如果设置了setOnClickListener,就会调用onClick方法。
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;
}
至此,VIew的事件分发流程终于告一段落。