
什么是事件?事件是用户触摸手机屏幕,引起的一系列touchEvent,包括ACTION_DOWN、ACTION_MOVE、ACTION_UP、ACTION_CANCEL等,这些action组合后变成点击事件、长按事件等。
在这篇文章中,用打Log测试的方法来了解AndroID touchEvent 事件分发,拦截,处理过程。虽然看了一些其他的文章和源码及相关的资料,但是还是觉得需要打下Log和画图来了解一下,不然很容易忘记了事件传递的整个过程。所以写下这篇文章,达到看完这篇文章基本可以了解整个过程,并且可以自己画图画出来给别人看。
先看几个类,主要是画出一个3个VIEwGroup叠加的界面,并在事件分发、拦截、处理时打下Log.
GitHub地址:https://github.com/libill/TouchEventDemo
一、通过打log分析事件分发这里在一个Activity上添加三个VIEwGroup来分析,这里值得注意的是Activity、VIEw是没有onIntercepttouchEvent方法的。
一、了解Activity、VIEwGroup1、VIEwGroup2、VIEwGroup3四个类activity_main.xml
<?xml version="1.0" enCoding="utf-8"?> <androID.support.constraint.ConstraintLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:app="http://schemas.androID.com/apk/res-auto" xmlns:tools="http://schemas.androID.com/tools" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" tools:context="com.touchevent.demo.MyActivity"> <com.touchevent.demo.VIEwGroup1 androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:background="@color/colorAccent"> <com.touchevent.demo.VIEwGroup2 androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:layout_margin="50dp" androID:background="@color/colorPrimary"> <com.touchevent.demo.VIEwGroup3 androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:layout_margin="50dp" androID:background="@color/colorPrimaryDark"> </com.touchevent.demo.VIEwGroup3> </com.touchevent.demo.VIEwGroup2> </com.touchevent.demo.VIEwGroup1> </androID.support.constraint.ConstraintLayout> 主界面:MainActivity.java
public class MyActivity extends AppCompatActivity { private final static String TAG = MyActivity.class.getname(); @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); } @OverrIDe public boolean dispatchtouchEvent(MotionEvent ev) { Log.i(TAG,"dispatchtouchEvent action:" + StringUtils.getMotionEventname(ev)); boolean superReturn = super.dispatchtouchEvent(ev); Log.d(TAG,"dispatchtouchEvent action:" + StringUtils.getMotionEventname(ev) + " " + superReturn); return superReturn; } @OverrIDe public boolean ontouchEvent(MotionEvent ev) { Log.i(TAG,"ontouchEvent action:" + StringUtils.getMotionEventname(ev)); boolean superReturn = super.ontouchEvent(ev); Log.d(TAG,"ontouchEvent action:" + StringUtils.getMotionEventname(ev) + " " + superReturn); return superReturn; } }三个VIEwGroup,里面的代码完全一样:VIEwGroup1.java,VIEwGroup2.java,VIEwGroup3.java。由于代码一样所以只贴其中一个类。
public class VIEwGroup1 extends linearLayout { private final static String TAG = VIEwGroup1.class.getname(); public VIEwGroup1(Context context) { super(context); } public VIEwGroup1(Context context,AttributeSet attrs) { super(context,attrs); } @OverrIDe public boolean dispatchtouchEvent(MotionEvent ev) { Log.i(TAG,"dispatchtouchEvent action:" + StringUtils.getMotionEventname(ev) + " " + superReturn); return superReturn; } @OverrIDe public boolean onIntercepttouchEvent(MotionEvent ev) { Log.i(TAG,"onIntercepttouchEvent action:" + StringUtils.getMotionEventname(ev)); boolean superReturn = super.onIntercepttouchEvent(ev); Log.d(TAG,"onIntercepttouchEvent action:" + StringUtils.getMotionEventname(ev) + " " + superReturn); return superReturn; } @OverrIDe public boolean ontouchEvent(MotionEvent ev) { Log.i(TAG,"ontouchEvent action:" + StringUtils.getMotionEventname(ev) + " " + superReturn); return superReturn; } }二、不拦截处理任何事件添加没有拦截处理任何事件的代码,看看事件是怎么传递的,选择Info,查看Log.
从流程图可以看出,事件分发从Activity开始,然后分发到VIEwGroup,在这个过程中,只要VIEwGroup没有拦截处理,最后还是会回到Activity的ontouchEvent方法。
三、VIEwGroup2的dispatchtouchEvent返回true把VIEwGroup2.java的dispatchtouchEvent修改一下,return 返回true使事件不在分发
@OverrIDepublic boolean dispatchtouchEvent(MotionEvent ev) { Log.i(TAG,"dispatchtouchEvent action:" + StringUtils.getMotionEventname(ev)); Log.d(TAG,"onIntercepttouchEvent action:" + StringUtils.getMotionEventname(ev) + " " + true); return true;}此时的Log
从图片可以看出,当VIEwGroupon2的dispatchtouchEvent返回true后,事件不会再分发传送到VIEwGroup3了,也不会分发到Activity的ontouchEvent了。而是事件到了VIEwGroupon2的dispatchtouchEvent后,就停止了。dispatchtouchEvent返回true表示着事件不用再分发下去了。
四、VIEwGroup2的onIntercepttouchEvent返回true把VIEwGroup2.java的onIntercepttouchEvent修改一下,return 返回true把事件拦截了
@OverrIDepublic boolean dispatchtouchEvent(MotionEvent ev) { Log.i(TAG,"dispatchtouchEvent action:" + StringUtils.getMotionEventname(ev)); boolean superReturn = super.dispatchtouchEvent(ev); Log.d(TAG,"dispatchtouchEvent action:" + StringUtils.getMotionEventname(ev) + " " + superReturn); return superReturn;}@OverrIDepublic boolean onIntercepttouchEvent(MotionEvent ev) { Log.i(TAG,"onIntercepttouchEvent action:" + StringUtils.getMotionEventname(ev)); Log.d(TAG,"onIntercepttouchEvent action:" + StringUtils.getMotionEventname(ev) + " " + true); return true;}此时的Log
可以看出VIEwGroup2拦截了事件,就不会继续分发到VIEwGroup3;而且VIEwGroup3拦截了事件又不处理事件,会把事件传递到Activity的ontouchEvent方法。
五、VIEwGroup2的onIntercepttouchEvent、ontouchEvent返回true把VIEwGroup2.java的ontouchEvent修改一下,return 返回true把事件处理了
@OverrIDepublic boolean onIntercepttouchEvent(MotionEvent ev) { Log.i(TAG,"onIntercepttouchEvent action:" + StringUtils.getMotionEventname(ev) + " " + true); return true;}@OverrIDepublic boolean ontouchEvent(MotionEvent ev) { Log.i(TAG,"ontouchEvent action:" + StringUtils.getMotionEventname(ev)); Log.d(TAG,"ontouchEvent action:" + StringUtils.getMotionEventname(ev) + " " + true); return true;}从流程可以总结出,当VIEwGroup2的onIntercepttouchEvent、ontouchEvent都返回true时,事件最终会走到VIEwGroup2的ontouchEvent方法处理事件,后续的事件都会走到这里来。
上面通过log分析很清楚了,是不是就这样够了?其实还不行,还要从源码的角度去分析下,为什么事件会这样分发。
二、通过源码分析事件分发一、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);}onUserInteraction方法
public voID onUserInteraction() {}从代码可以了解
调用Activity的onUserInteraction方法,action为down时会进去onUserInteraction方法,但是这个是空方法不做任何事情,可以忽略。
调用window的superdispatchtouchEvent方法,返回true时事件分发处理结束,否则会调用Activity的ontouchEvent方法。
调用Activity的ontouchEvent方法,进入这个条件的方法是window的superdispatchtouchEvent方法返回false。从上面的分析(二、不拦截处理任何事件)可以知道,所有子VIEw的dispatchtouchEvent、onIntercepttouchEvent、ontouchEvent都返回false时会调动Activity的ontouchEvent方法,这个时候也是使window的superdispatchtouchEvent方法返回false成立。
二、window的superdispatchtouchEventActivity的getwindow方法
public Window getwindow() { return mWindow;}mWindow是如何赋值的?
是在Activity的attach方法赋值的,其实mWindow是PhoneWindow。
Activity的attach方法
final voID attach(Context context,ActivityThread aThread,Instrumentation instr,IBinder token,int IDent,Application application,Intent intent,ActivityInfo info,CharSequence Title,Activity parent,String ID,NonConfigurationInstances lastNonConfigurationInstances,Configuration config,String referrer,IVoiceInteractor voiceInteractor,Window window,ActivityConfigCallback activityConfigCallback) { attachBaseContext(context); mFragments.attachHost(null /*parent*/); mWindow = new PhoneWindow(this,window,activityConfigCallback); mWindow.setwindowControllerCallback(this); mWindow.setCallback(this); mWindow.setonWindowdismissedCallback(this); mWindow.getLayoutInflater().setPrivateFactory(this); ...}PhoneWindow的superdispatchtouchEvent方法
private DecorVIEw mDecor;@OverrIDepublic boolean superdispatchtouchEvent(MotionEvent event) { return mDecor.superdispatchtouchEvent(event);}DevorVIEw的superdispatchtouchEvent
public boolean superdispatchtouchEvent(MotionEvent event) { return super.dispatchtouchEvent(event);}而mDecor是一个继承FrameLayout的DecorVIEw,就这样把事件分发到VIEwGroup上了。
三、VIEwGroup的dispatchtouchEvent3.1 VIEwGroup拦截事件的情况 // 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; }这里分为2种情况会判断是否需要拦截,也就是当某一条件成立时,会执行onIntercepttouchEvent判断是否需要拦截事件。
当actionMasked == MotionEvent.ACTION_DOWN时。
当mFirsttouchTarget != null时。mFirsttouchTarget是成功处理事件的VIEwGroup的子VIEw,也就是VIEwGroup的子VIEw在以下情况返回true时,这个在log分析流程图轻易得到:
2.1 dispatchtouchEvent返回true
2.2 如果子VIEw是VIEwGroup时,onIntercepttouchEvent、ontouchEvent返回true
另外还有一种情况是disallowIntercept为true时,intercepted直接赋值false不进行拦截。FLAG_disALLOW_INTERCEPT是通过requestdisallowIntercepttouchEvent方法来设置的,用于在子VIEw中设置,设置后VIEwGroup只能拦截down事件,无法拦截其他move、up、cancel事件。为什么VIEwGroup还能拦截down事件呢?因为VIEwGroup在down事件时进行了重置,看看以下代码
// 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 // due to an app switch,ANR,or some other state change. cancelAndCleartouchTargets(ev); resettouchState();}private voID resettouchState() { cleartouchTargets(); resetCancelNextUpFlag(this); mGroupFlags &= ~FLAG_disALLOW_INTERCEPT; mnestedScrollAxes = SCRolL_AXIS_NONE;}通过源码可以了解到,VIEwGroup拦截事件后,不再调用onIntercepttouchEvent,而是直接交给mFirsttouchTarget的ontouchEvent处理,如果该ontouchEvent不处理最终会交给Activity的ontouchEvent。
3.2 VIEwGroup不拦截事件的情况VIEwGroup不拦截事件时,会遍历子VIEw,使事件分发到子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 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. 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) { // 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,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; }}3.2.1 寻找可接收事件的子VIEw通过canVIEwReceivePointerEvents判断子VIEw是否能够接收到点击事件。必须符合2种情况,缺一不可:1、点击事件的坐标落在在子VIEw的区域内;2、子VIEw没有正在播放动画。满足条件后,调用dispatchtransformedtouchEvent,其实也是调用子VIEw的dispatchtouchEvent。
private static boolean canVIEwReceivePointerEvents(@NonNull VIEw child) { return (child.mVIEwFlags & VISIBIliTY_MASK) == VISIBLE || child.getAnimation() != null;}protected boolean istransformedtouchPointInVIEw(float x,float y,VIEw child,PointF outLocalPoint) { final float[] point = getTempPoint(); point[0] = x; point[1] = y; transformPointToVIEwLocal(point,child); final boolean isInVIEw = child.pointInVIEw(point[0],point[1]); if (isInVIEw && outLocalPoint != null) { outLocalPoint.set(point[0],point[1]); } return isInVIEw;}private boolean dispatchtransformedtouchEvent(MotionEvent event,boolean cancel,int desiredPointerIDBits) { final boolean handled; final int oldAction = event.getAction(); 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; } ... // Perform any necessary transformations and dispatch. if (child == null) { handled = super.dispatchtouchEvent(transformedEvent); } else { final float offsetX = mScrollX - child.mleft; final float offsetY = mScrollY - child.mtop; transformedEvent.offsetLocation(offsetX,offsetY); if (! child.hasIDentityMatrix()) { transformedEvent.transform(child.getInverseMatrix()); } handled = child.dispatchtouchEvent(transformedEvent); } // Done. transformedEvent.recycle(); return handled;}当dispatchtransformedtouchEvent返回true时,结束for循环遍历,赋值newtouchTarget,相当于发现了可以接收事件的VIEw,不用再继续找了。
newtouchTarget = addtouchTarget(child,IDBitsToAssign);alreadydispatchedToNewtouchTarget = true;break;在addtouchTarget方法赋值mFirsttouchTarget。
private touchTarget addtouchTarget(@NonNull VIEw child,int pointerIDBits) { final touchTarget target = touchTarget.obtain(child,pointerIDBits); target.next = mFirsttouchTarget; mFirsttouchTarget = target; return target;}3.2.2 VIEwGroup自己处理事件另一种情况是mFirsttouchTarget为空时,VIEwGroup自己处理事件,这里注意第三个参数为null,VIEwGroup的super.dispatchtouchEvent将调用VIEw的dispatchtouchEvent。
if (mFirsttouchTarget == null) { // No touch targets so treat this as an ordinary vIEw. handled = dispatchtransformedtouchEvent(ev,canceled,null,touchTarget.ALL_POINTER_IDS);}3.3 VIEw处理点击事件的过程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;}首先使用onFiltertouchEventForSecurity方法过滤不符合应用安全策略的触摸事件。
public boolean onFiltertouchEventForSecurity(MotionEvent event) { //noinspection RedundantIfStatement if ((mVIEwFlags & FILTER_touches_WHEN_OBSCURED) != 0 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { // Window is obscured,drop this touch. return false; } return true; }mOntouchListener != null判断是否设置了OntouchEvent,设置了就执行mOntouchListener.ontouch并返回true,不再执行ontouchEvent。这里得出OntouchEvent的优先级高于OntouchEvent,便于使用setontouchListener设置处理点击事件。
另一种情况是进入ontouchEvent进行处理。
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; } ... }当VIEw不可用时,依然会处理事件,只是看起来不可用。
接着执行mtouchDelegate.ontouchEvent
if (mtouchDelegate != null) { if (mtouchDelegate.ontouchEvent(event)) { return true; }}下面看看up事件是怎么处理的
/** * <p>Indicates this vIEw can display a tooltip on hover or long press.</p> * {@hIDe} */static final int tooltip = 0x40000000;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(); } } } 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 true;}从上面代码可以了解,clickable、tooltip(长按)有一个为true时,就会消耗事件,使ontouchEvent返回true。其中PerformClick内部调用了performClick方法。
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;}如果VIEw设置了OnClickListener,那performClick会调用内部的onClick方法。
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;}通过setonClickListener设置clickable,通过setonLongClickListener设置LONG_CliCKABLE长按事件。设置后使得ontouchEvent返回true。到这里我们已经分析完成点击事件的分发过程了。
本文地址:http://libill.github.io/2019/09/09/android-touch-event/
本文参考以下内容:
1、《AndroID开发艺术探索》
总结以上是内存溢出为你收集整理的一文读懂 Android TouchEvent 事件分发、拦截、处理过程全部内容,希望文章能够帮你解决一文读懂 Android TouchEvent 事件分发、拦截、处理过程所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)