Android事件的分发机制详解
在分析Android事件分发机制前,明确android的两大基础控件类型:View和ViewGroup。View即普通的控件,没有子布局的,如Button、TextView.ViewGroup继承自View,表示可以有子控件,如Linearlayout、Listview这些。今天我们先来了解View的事件分发机制。
先看下代码,非常简单,只有一个Button,分别给它注册了OnClick和OnTouch的点击事件。
btn.setOnClickListener(newView.OnClickListener(){ @Override publicvoidonClick(Viewv){ Log.i("Tag","ThisisbuttononClickevent"); } }); btn.setOnTouchListener(newView.OnTouchListener(){ @Override publicbooleanonTouch(Viewv,MotionEventevent){ Log.i("Tag","ThisisbuttononTouchaction"+event.getAction()); returnfalse; } });
运行一下项目,结果如下:
I/Tag:ThisisbuttononTouchaction0
I/Tag:ThisisbuttononTouchaction2
I/Tag:ThisisbuttononTouchaction2
I/Tag:ThisisbuttononTouchaction1
I/Tag:ThisisbuttononClickevent
可以看到,onTouch是有先于onClick执行的,因此事件的传递顺序是先onTouch,在到OnClick。具体为什么这样,下面会通过源码来说明。这时,我们可能注意到了,onTouch的方法是有返回值,这里是返回false,我们将它改为true再运行一次,结果如下:
I/Tag:ThisisbuttononTouchaction0
I/Tag:ThisisbuttononTouchaction2
I/Tag:ThisisbuttononTouchaction2
I/Tag:ThisisbuttononTouchaction2
I/Tag:ThisisbuttononTouchaction1
对比两次结果,我们发现onClick方法不再执行,为什么会这样,下面我将通过源码给大家一步步理清这个思路。
查看源码时,首先要知道所有View类型控件事件入口都是dispatchTouchEvent(),所以我们直接进入到View这个类里面的dispatchTouchEvent()方法看一下。
publicbooleandispatchTouchEvent(MotionEventevent){ //Iftheeventshouldbehandledbyaccessibilityfocusfirst. if(event.isTargetAccessibilityFocus()){ //Wedon'thavefocusornovirtualdescendanthasit,donothandletheevent. if(!isAccessibilityFocusedViewOrHost()){ returnfalse; } //Wehavefocusandgottheevent,thenusenormaleventdispatch. event.setTargetAccessibilityFocus(false); } booleanresult=false; if(mInputEventConsistencyVerifier!=null){ mInputEventConsistencyVerifier.onTouchEvent(event,0); } finalintactionMasked=event.getActionMasked(); if(actionMasked==MotionEvent.ACTION_DOWN){ //Defensivecleanupfornewgesture stopNestedScroll(); } if(onFilterTouchEventForSecurity(event)){ //noinspectionSimplifiableIfStatement ListenerInfoli=mListenerInfo; if(li!=null&&li.mOnTouchListener!=null &&(mViewFlags&ENABLED_MASK)==ENABLED &&li.mOnTouchListener.onTouch(this,event)){ result=true; } if(!result&&onTouchEvent(event)){ result=true; } } if(!result&&mInputEventConsistencyVerifier!=null){ mInputEventConsistencyVerifier.onUnhandledEvent(event,0); } //Cleanupafternestedscrollsifthisistheendofagesture; //alsocancelitifwetriedanACTION_DOWNbutwedidn'twanttherest //ofthegesture. if(actionMasked==MotionEvent.ACTION_UP|| actionMasked==MotionEvent.ACTION_CANCEL|| (actionMasked==MotionEvent.ACTION_DOWN&&!result)){ stopNestedScroll(); } returnresult; }
从源码第25行处可以看到,mOnTouchListener.onTouch()的方法首先被执行,如果li!=null&&li.mOnTouchListener!=null&&(mViewFlags&ENABLED_MASK)==ENABLED&&li.mOnTouchListener.onTouch(this,event)都为真的话,result赋值为true,否则就执行onTouchEvent(event)方法。
从上面可以看到要符合条件有四个,
1、ListenerInfoli,它是view中的一个静态类,里面定义view的事件的监听等等,所以有涉及到view的事件,ListenerInfo都会被实例化,因此li不为null
2、mOnTouchiListener是在setOnTouchListener方法里面赋值的,只要touch事件被注册,mOnTouchiListener一定不会null
3、(mViewFlags&ENABLED_MASK)==ENABLED,是判断当前点击的控件是否是enable的,button默认为enable,这个条件也恒定为true,
4、重点来了,li.mOnTouchListener.onTouch(this,event)就是回调控件onTouch方法,当这个条件也为true时,result=true,onTouchEvent(event)将不会被执行。如果onTouch返回false,就会再执行onTouchEvent(event)方法。
我们接着再进入到onTouchEvent方法查看源码。
publicbooleanonTouchEvent(MotionEventevent){ finalfloatx=event.getX(); finalfloaty=event.getY(); finalintviewFlags=mViewFlags; finalintaction=event.getAction(); if((viewFlags&ENABLED_MASK)==DISABLED){ if(action==MotionEvent.ACTION_UP&&(mPrivateFlags&PFLAG_PRESSED)!=0){ setPressed(false); } //Adisabledviewthatisclickablestillconsumesthetouch //events,itjustdoesn'trespondtothem. return(((viewFlags&CLICKABLE)==CLICKABLE ||(viewFlags&LONG_CLICKABLE)==LONG_CLICKABLE) ||(viewFlags&CONTEXT_CLICKABLE)==CONTEXT_CLICKABLE); } if(mTouchDelegate!=null){ if(mTouchDelegate.onTouchEvent(event)){ returntrue; } } if(((viewFlags&CLICKABLE)==CLICKABLE|| (viewFlags&LONG_CLICKABLE)==LONG_CLICKABLE)|| (viewFlags&CONTEXT_CLICKABLE)==CONTEXT_CLICKABLE){ switch(action){ caseMotionEvent.ACTION_UP: booleanprepressed=(mPrivateFlags&PFLAG_PREPRESSED)!=0; if((mPrivateFlags&PFLAG_PRESSED)!=0||prepressed){ //takefocusifwedon'thaveitalreadyandweshouldin //touchmode. booleanfocusTaken=false; if(isFocusable()&&isFocusableInTouchMode()&&!isFocused()){ focusTaken=requestFocus(); } if(prepressed){ //Thebuttonisbeingreleasedbeforeweactually //showeditaspressed.Makeitshowthepressed //statenow(beforeschedulingtheclick)toensure //theuserseesit. setPressed(true,x,y); } if(!mHasPerformedLongPress&&!mIgnoreNextUpEvent){ //Thisisatap,soremovethelongpresscheck removeLongPressCallback(); //Onlyperformtakeclickactionsifwewereinthepressedstate if(!focusTaken){ //UseaRunnableandpostthisratherthancalling //performClickdirectly.Thisletsothervisualstate //oftheviewupdatebeforeclickactionsstart. if(mPerformClick==null){ mPerformClick=newPerformClick(); } if(!post(mPerformClick)){ performClick(); } } } if(mUnsetPressedState==null){ mUnsetPressedState=newUnsetPressedState(); } if(prepressed){ postDelayed(mUnsetPressedState, ViewConfiguration.getPressedStateDuration()); }elseif(!post(mUnsetPressedState)){ //Ifthepostfailed,unpressrightnow mUnsetPressedState.run(); } removeTapCallback(); } mIgnoreNextUpEvent=false; break; caseMotionEvent.ACTION_DOWN: mHasPerformedLongPress=false; if(performButtonActionOnTouchDown(event)){ break; } //Walkupthehierarchytodetermineifwe'reinsideascrollingcontainer. booleanisInScrollingContainer=isInScrollingContainer(); //Forviewsinsideascrollingcontainer,delaythepressedfeedbackfor //ashortperiodincasethisisascroll. if(isInScrollingContainer){ mPrivateFlags|=PFLAG_PREPRESSED; if(mPendingCheckForTap==null){ mPendingCheckForTap=newCheckForTap(); } mPendingCheckForTap.x=event.getX(); mPendingCheckForTap.y=event.getY(); postDelayed(mPendingCheckForTap,ViewConfiguration.getTapTimeout()); }else{ //Notinsideascrollingcontainer,soshowthefeedbackrightaway setPressed(true,x,y); checkForLongClick(0); } break; caseMotionEvent.ACTION_CANCEL: setPressed(false); removeTapCallback(); removeLongPressCallback(); mInContextButtonPress=false; mHasPerformedLongPress=false; mIgnoreNextUpEvent=false; break; caseMotionEvent.ACTION_MOVE: drawableHotspotChanged(x,y); //Belenientaboutmovingoutsideofbuttons if(!pointInView(x,y,mTouchSlop)){ //Outsidebutton removeTapCallback(); if((mPrivateFlags&PFLAG_PRESSED)!=0){ //Removeanyfuturelongpress/tapchecks removeLongPressCallback(); setPressed(false); } } break; } returntrue; } returnfalse; }
从源码的21行我们可以看出,该控件可点击就会进入到switch判断中,当我们触发了手指离开的实际,则会进入到MotionEvent.ACTION_UP这个case当中。我们接着往下看,在源码的50行,调用到了mPerformClick()方法,我们继续进入到这个方法的源码看看。
publicbooleanperformClick(){ finalbooleanresult; finalListenerInfoli=mListenerInfo; if(li!=null&&li.mOnClickListener!=null){ playSoundEffect(SoundEffectConstants.CLICK); li.mOnClickListener.onClick(this); result=true; }else{ result=false; } sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); returnresult; }
现在我们可以看到,只要ListenerInfo和mOnClickListener不为null就会调用onClick这个方法,之前说过,只要有监听事件,ListenerInfo就不为null,带mOnClickListener又是在哪里赋值呢?我们再继续看下它的源码。
publicvoidsetOnClickListener(@NullableOnClickListenerl){ if(!isClickable()){ setClickable(true); } getListenerInfo().mOnClickListener=l; }
看到这里一切就清楚了,当我们调用setOnClickListener方法来给按钮注册一个点击事件时,就会给mOnClickListener赋值。整个分发事件的顺序是onTouch()-->onTouchEvent(event)-->performClick()-->OnClick()。
现在我们可以解决之前的问题。
1、onTouch方法是优先于OnClick,所以是执行了onTouch,再执行onClick。
2、无论是dispatchTouchEvent还是onTouchEvent,如果返回true表示这个事件已经被消费、处理了,不再往下传了。在dispathTouchEvent的源码里可以看到,如果onTouchEvent返回了true,那么它也返回true。如果dispatchTouchEvent在执行onTouch监听的时候,onTouch返回了true,那么它也返回true,这个事件提前被onTouch消费掉了。就不再执行onTouchEvent了,更别说onClick监听了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。