赞
踩
下面举出一个实例来理解事件拦截,ViewGroupA最外层的ViewGroup,ViewGroupB是中间的ViewGroup,最里面是ViewC,是一个View。
重写ViewGroupA、ViewGroupB中的dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent。viewC中的dispatchTouchEvent、onTouchEvent。
//ViewGroupA、ViewGroupB @Override public boolean dispatchTouchEvent(MotionEvent ev) { Log.d(TAG, "A dispatchTouchEvent" + ev.getAction()); return super.dispatchTouchEvent(ev); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { Log.d(TAG, "A onInterceptTouchEvent" + ev.getAction()); return super.onInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent event) { Log.d(TAG, "A onTouchEvent" + event.getAction()); return super.onTouchEvent(event); }
//viewC
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
Log.d(TAG, "C dispatchTouchEvent" + event.getAction());
return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d(TAG, "C onTouchEvent" + event.getAction());
return super.onTouchEvent(event);
}
点击View,查看打印输出。
2022-03-10 00:04:04.181 10651-10651/cn.study.study20220109 D/SJLJ: A dispatchTouchEvent0
2022-03-10 00:04:04.181 10651-10651/cn.study.study20220109 D/SJLJ: A onInterceptTouchEvent0
2022-03-10 00:04:04.181 10651-10651/cn.study.study20220109 D/SJLJ: B dispatchTouchEvent0
2022-03-10 00:04:04.181 10651-10651/cn.study.study20220109 D/SJLJ: B onInterceptTouchEvent0
2022-03-10 00:04:04.181 10651-10651/cn.study.study20220109 D/SJLJ: C dispatchTouchEvent0
2022-03-10 00:04:04.181 10651-10651/cn.study.study20220109 D/SJLJ: C onTouchEvent0
2022-03-10 00:04:04.181 10651-10651/cn.study.study20220109 D/SJLJ: B onTouchEvent0
2022-03-10 00:04:04.182 10651-10651/cn.study.study20220109 D/SJLJ: A onTouchEvent0
从上面的结果,可以得出,事件的传递顺序,A→B→C,先执行dispatchTouchEvent再执行onInterceptTouchEvent。事件的处理顺序是,C→B→A。
事件传递的返回值:True拦截,不继续;False,不拦截,继续流程。
事件处理的返回值:True,处理了,False,给上级处理。
改动A中的onInterceptTouchEvent返回True,查看打印结果。
2022-03-10 20:48:26.188 27705-27705/cn.study.study20220109 D/SJLJ: A dispatchTouchEvent0
2022-03-10 20:48:26.188 27705-27705/cn.study.study20220109 D/SJLJ: A onInterceptTouchEvent0
2022-03-10 20:48:26.189 27705-27705/cn.study.study20220109 D/SJLJ: A onTouchEvent0
A把事件拦截了,自己对事件进行了处理。致使事件传递不到里面,更不用说处理事件了。
改动B中的onInterceptTouchEvent返回True,查看打印结果。
2022-03-10 20:56:23.615 30878-30878/cn.study.study20220109 D/SJLJ: A dispatchTouchEvent0
2022-03-10 20:56:23.615 30878-30878/cn.study.study20220109 D/SJLJ: A onInterceptTouchEvent0
2022-03-10 20:56:23.615 30878-30878/cn.study.study20220109 D/SJLJ: B dispatchTouchEvent0
2022-03-10 20:56:23.615 30878-30878/cn.study.study20220109 D/SJLJ: B onInterceptTouchEvent0
2022-03-10 20:56:23.615 30878-30878/cn.study.study20220109 D/SJLJ: B onTouchEvent0
2022-03-10 20:56:23.616 30878-30878/cn.study.study20220109 D/SJLJ: A onTouchEvent0
B拦截事件,B进行处理,B onTouchEvent返回False,不消耗事件,继续调用A的onTouchEvent方法。由于B的拦截,事件传递不到C。
改变C中的onTouchEvent返回True,查看打印结果。
2022-03-10 21:44:39.011 16371-16371/cn.study.study20220109 D/SJLJ: A dispatchTouchEvent0 2022-03-10 21:44:39.011 16371-16371/cn.study.study20220109 D/SJLJ: A onInterceptTouchEvent0 2022-03-10 21:44:39.011 16371-16371/cn.study.study20220109 D/SJLJ: B dispatchTouchEvent0 2022-03-10 21:44:39.011 16371-16371/cn.study.study20220109 D/SJLJ: B onInterceptTouchEvent0 2022-03-10 21:44:39.011 16371-16371/cn.study.study20220109 D/SJLJ: C dispatchTouchEvent0 2022-03-10 21:44:39.011 16371-16371/cn.study.study20220109 D/SJLJ: C onTouchEvent0 2022-03-10 21:44:39.087 16371-16371/cn.study.study20220109 D/SJLJ: A dispatchTouchEvent2 2022-03-10 21:44:39.088 16371-16371/cn.study.study20220109 D/SJLJ: A onInterceptTouchEvent2 2022-03-10 21:44:39.088 16371-16371/cn.study.study20220109 D/SJLJ: B dispatchTouchEvent2 2022-03-10 21:44:39.088 16371-16371/cn.study.study20220109 D/SJLJ: B onInterceptTouchEvent2 2022-03-10 21:44:39.088 16371-16371/cn.study.study20220109 D/SJLJ: C dispatchTouchEvent2 2022-03-10 21:44:39.088 16371-16371/cn.study.study20220109 D/SJLJ: C onTouchEvent2 2022-03-10 21:44:39.089 16371-16371/cn.study.study20220109 D/SJLJ: A dispatchTouchEvent1 2022-03-10 21:44:39.089 16371-16371/cn.study.study20220109 D/SJLJ: A onInterceptTouchEvent1 2022-03-10 21:44:39.089 16371-16371/cn.study.study20220109 D/SJLJ: B dispatchTouchEvent1 2022-03-10 21:44:39.089 16371-16371/cn.study.study20220109 D/SJLJ: B onInterceptTouchEvent1 2022-03-10 21:44:39.089 16371-16371/cn.study.study20220109 D/SJLJ: C dispatchTouchEvent1 2022-03-10 21:44:39.089 16371-16371/cn.study.study20220109 D/SJLJ: C onTouchEvent1
事件被C消耗,C处理了down、move、up事件。通过上面的实例我们对事件分发、拦截、处理有了大致的了解,正常情况下,一旦事件被这个View消耗,则后续事件序列都给这个View。
点击事件的事件分发,当一个MotionEvent产生后,系统需要把这个事件传递给一个具体的View,这个传递过程就是分发过程。分发过程有三个比较重要的方法来完成:dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent。
dispatchTouchEvent
用来进行事件的分发。
onInterceptTouchEvent
在dispatchTouchEvent 方法中,用来判断是否拦截某个事件。返回结果表示是否拦截当前的事件。
onTouchEvent
在dispatchTouchEvent 方法中调用,用来处理点击事件,返回结果表示是否消耗当前事件,如果不消耗,则在同一个事件序列中,当前View无法再次接受到事件。
下面通过简化代码来更好理解上面的三个方法的关系:
public boolean dispatchTouchEvent(MotionEvent event) {
boolean consume = false;
if (onInterceptTouchEvent(event)) {
consume = onTouchEvent(event);
} else {
consume = child.dispatchTouchEvent(event);
}
}
上面方法大致意思是,当一个根ViewGroup,点击事件产生后,它的dispatchTouchEvent会被调用,检测onInterceptTouchEvent方法返回值,如果为True,拦截事件,事件会交给这个ViewGroup处理;如果为False,不拦截事件,将当前事件传递给它的子元素,子元素又会调用dispatchTouchEvent方法,如此反复直到事件被最终处理。
点击事件的传递过程:activity→window→View。
接下来,进行事件分发的源码分析。
当一个点击操作发生时,事件最先传递给当前Activity,Activity的dispatchTouchEvent来进行事件传递,具体工作由window来完成。window会将事件传递给decor view。
Activity中的dispatchTouchEvent方法。
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
事件由window进行分发,如果为true,则整个事件结束;如果为false,事件没有view处理,所有的view的onTouchEvent都返回了false,则activity的onTouchEvent就会被调用。
window是如何将事件传递给ViewGroup。window是一个抽象类,window的实现类是PhoneWindow。
phonewindow#superDispatchTouchEvent
public boolean superDispatchTouchEvent(MotionEvent ev){
return mDecor.superDispatchTouchEvent(ev);
}
从上面代码可以看出PhoneWindow将事件传递给DecorView。事件已经传递到了顶级View。
ViewGroup对点击事件的分发过程,主要在ViewGroup的dispatchTouchEvent。下面将对源码进行分段分析。
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;
}
上面的代码,判断是否要拦截点击事件。对mFirstTouchTarget 解释,当事件由ViewGroup的子元素成功处理时,mFirstTouchTarget 会被赋值并指向子元素。当ViewGroup不拦截事件并将事件交由子元素处理时,mFirstTouchTarget != null成立。
着重说明一下FLAG_DISALLOW_INTERCEPT这个值,通过requestDisallowInterceptTouchEvent方法来设置,FLAG_DISALLOW_INTERCEPT设置后,ViewGroup将无法拦截除了ACTION_DOWN以外的其他点击事件。为什么拦截不了
ACTION_DOWN?因为在判断拦截之前,ACTION_DOWN事件会重置FLAG_DISALLOW_INTERCEPT这个标志位。当面对ACTION_DOWN事件时,ViewGroup总会调用自己的onInterceptTouchEvent方法来询问自己是否要拦截。
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();
}
上面的代码resetTouchState方法对FLAG_DISALLOW_INTERCEPT进行了重置。
requestDisallowInterceptTouchEvent中的代码,通过位运算来设置是否拦截
mGroupFlags |= FLAG_DISALLOW_INTERCEPT; 设置不允许拦截
mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;设置允许拦截
当ViewGroup决定拦截事件后,后续的点击事件将会默认交给它处理且不再调用自己的onInterceptTouchEvent方法。FLAG_DISALLOW_INTERCEPT的作用是让ViewGroup不在拦截事件,除ACTION_DOWN事件。
当ViewGroup不拦截事件,事件将会传递到它的子View。
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 (!child.canReceivePointerEvents() || !isTransformedTouchPointInView(x, y, child, null)) { 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; } 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(); newTouchTarget = addTouchTarget(child, idBitsToAssign); alreadyDispatchedToNewTouchTarget = true; break; }
对上面的这段代码进行解释,先遍历ViewGroup的所有子元素,判断子元素是否能够接收到点击事件。是否能够接收点击事件主要由两点:子元素是否在播动画和点击事件的坐标是否落在子元素的区域内。如果某个子元素满足这两个条件,则事件会传递给它来处理。从上面的代码中,找到dispatchTransformedTouchEvent,这个方法调用的是子元素的dispatchTouchEvent方法。在上面的代码中child不为null,事件将会交由子元素处理。
dispatchTransformedTouchEvent部分代码
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
如果子元素的dispatchTouchEvent返回true,则说明事件被消耗了,mFirstTouchTarget被复且同时跳出for循环。
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
如果遍历所有的子元素后,事件都没有被处理,这包含两种情况。一是ViewGroup没有子元素,二是子元素处理了点击事件,但在dispatchTouchEvent中返回了false,一般原因是子元素在onTouchEvent中反悔了false。这两种情况,ViewGroup会自己处理点击事件。
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
上面代码中,child为null,将会调用super.dispatchTouchEvent(event),由于ViewGroup继承于View,view的dispatchTouchEvent将会被调用。ViewGroup将会自己消化事件。
这里是View的dispatchTouchEvent方法 public boolean dispatchTouchEvent(MotionEvent event) { ....... boolean result = false; 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; }
View是一个单独的元素,它没有必要向其他元素传递事件,只能自己处理。首先会判断有没有设置OnTouchListener,如果OnTouchListener中的onTouch方法返回true,那么onTouchEvent就不会被调用。
接下来看看onTouchEvent,当View处于不可用的状态下,View照样会消耗点击事件。
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;
}
继续往下来,如果view设置有代理,会执行TouchDelegate的onTouchEvent方法。
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
接下来,查看onTouchEvent中对点击事件的具体处理。
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; ......... if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) { switch (action) { case MotionEvent.ACTION_UP: mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; if ((viewFlags & TOOLTIP) == TOOLTIP) { handleTooltipUp(); } if (!clickable) { removeTapCallback(); removeLongPressCallback(); mInContextButtonPress = false; mHasPerformedLongPress = false; mIgnoreNextUpEvent = false; break; } 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)) { performClickInternal(); } } } ......... } mIgnoreNextUpEvent = false; break; } return true; }
从上面可以看出,只要View的CLICKABLE和LONG_CLICKABLE有一个true,它就会消耗这个事件,onTouchEvent返回True。当ACTION_UP事件发生时,触发performClick方法,若果设置了OnClickListener,那么onClick方法将会被调用。
public boolean performClick() { // We still need to call this method to handle the cases where performClick() was called // externally, instead of through performClickInternal() notifyAutofillManagerOnClick(); 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); notifyEnterOrExitForAutoFillIfNeeded(true); return result; }
最后说下LONG_CLICKABLE与CLICKABLE,这两个的值与具体的View有关,比如button是可点击的、TextView是不可点击的。setOnClickListener会自动将View的CLICKABLE设为true。setOnLongClickListener同理。
public void setOnClickListener(@Nullable OnClickListener l) {
if (!isClickable()) {
setClickable(true);
}
getListenerInfo().mOnClickListener = l;
}
public void setOnLongClickListener(@Nullable OnLongClickListener l) {
if (!isLongClickable()) {
setLongClickable(true);
}
getListenerInfo().mOnLongClickListener = l;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。