- 浏览: 65438 次
- 性别:
- 来自: 西安
文章分类
最新评论
Android源码分析-点击事件派发机制
概述
一直想写篇关于Android事件派发机制的文章,却一直没写,这两天刚好是周末,有时间了,想想写一篇吧,不然总是只停留在会用的层次上但是无法了解其内部机制。我用的是4.4源码,打开看看,挺复杂的,尤其是事件是怎么从Activity派发出来的,太费解了。了解Windows消息机制的人会发现,觉得Android的事件派发机制和Windows的消息派发机制挺像的,其实这是一种典型的消息“冒泡”机制,很多平台采用这个机制,消息最先到达最底层View,然后它先进行判断是不是它所需要的,否则就将消息传递给它的子View,这样一来,消息就从水底的气泡一样向上浮了一点距离,以此类推,气泡达到顶部和空气接触,破了(消息被处理了),当然也有气泡浮出到顶层了,还没破(消息无人处理),这个消息将由系统来处理,对于Android来说,会由Activity来处理。
Android点击事件的派发机制
1. 从Activity传递到底层View
点击事件用MotionEvent来表示,当一个点击操作发生时,事件最先传递给当前Activity,由Activity的dispatchTouchEvent来进行事件派发,具体的工作是由Activity内部的Window来完成的,Window会将事件传递给decor view,decor view一般就是当前界面的底层容器(即setContentView所设置的View),通过Activity.getWindow.getDecorView()可以获得。另外,看下面代码的的时候,主要看我注释的地方,代码很多很复杂,我无法一一说明,但是我注释的地方都是关键点,是博主仔细读代码总结出来的。
源码解读:
事件是由哪里传递给Activity的,这个我还不清楚,但是不要紧,我们从activity开始分析,已经足够我们了解它的内部实现了。
Code:Activity#dispatchTouchEvent
- /**
- *Calledtoprocesstouchscreenevents.Youcanoverridethisto
- *interceptalltouchscreeneventsbeforetheyaredispatchedtothe
- *window.Besuretocallthisimplementationfortouchscreenevents
- *thatshouldbehandlednormally.
- *
- *@paramevThetouchscreenevent.
- *
- *@returnbooleanReturntrueifthiseventwasconsumed.
- */
- publicbooleandispatchTouchEvent(MotionEventev){
- if(ev.getAction()==MotionEvent.ACTION_DOWN){
- //这个函数其实是个空函数,啥也没干,如果你没重写的话,不用关心
- onUserInteraction();
- }
- //这里事件开始交给Activity所附属的Window进行派发,如果返回true,整个事件循环就结束了
- //返回false意味着事件没人处理,所有人的onTouchEvent都返回了false,那么Activity就要来做最后的收场。
- if(getWindow().superDispatchTouchEvent(ev)){
- returntrue;
- }
- //这里,Activity来收场了,Activity的onTouchEvent被调用
- returnonTouchEvent(ev);
- }
Window是如何将事件传递给ViewGroup的
Code:Window#superDispatchTouchEvent
- /**
- *Usedbycustomwindows,suchasDialog,topassthetouchscreenevent
- *furtherdowntheviewhierarchy.Applicationdevelopersshould
- *notneedtoimplementorcallthis.
- *
- */
- publicabstractbooleansuperDispatchTouchEvent(MotionEventevent);
Abstract base class for a top-level window look and behavior policy. An instance of this class should be used as the top-level view added to the window manager. It provides standard UI policies such as a background, title area, default key processing, etc.
The only existing implementation of this abstract class is android.policy.PhoneWindow, which you should instantiate when needing a Window. Eventually that class will be refactored and a factory method added for creating Window instances without knowing about a particular implementation.
Code:PhoneWindow#superDispatchTouchEvent- @Override
- publicbooleansuperDispatchTouchEvent(MotionEventevent){
- returnmDecor.superDispatchTouchEvent(event);
- }
- privatefinalclassDecorViewextendsFrameLayoutimplementsRootViewSurfaceTaker
- //Thisisthetop-levelviewofthewindow,containingthewindowdecor.
- privateDecorViewmDecor;
- @Override
- publicfinalViewgetDecorView(){
- if(mDecor==null){
- installDecor();
- }
- returnmDecor;
- }
顺便说一下,平时Window用的最多的就是((ViewGroup)getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0)即通过Activity来得到内部的View。这个mDecor显然就是getWindow().getDecorView()返回的View,而我们通过setContentView设置的View是它的一个子View。目前事件传递到了DecorView 这里,由于DecorView 继承自FrameLayout且是我们的父View,所以最终事件会传递给我们的View,原因先不管了,换句话来说,事件肯定会传递到我们的View,不然我们的应用如何响应点击事件呢。不过这不是我们的重点,重点是事件到了我们的View以后应该如何传递,这是对我们更有用的。从这里开始,事件已经传递到我们的顶级View了,注意:顶级View实际上是最底层View,也叫根View。
2.底层View对事件的分发过程
点击事件到底层View(一般是一个ViewGroup)以后,会调用ViewGroup的dispatchTouchEvent方法,然后的逻辑是这样的:如果底层ViewGroup拦截事件即onInterceptTouchEvent返回true,则事件由ViewGroup处理,这个时候,如果ViewGroup的mOnTouchListener被设置,则会onTouch会被调用,否则,onTouchEvent会被调用,也就是说,如果都提供的话,onTouch会屏蔽掉onTouchEvent。在onTouchEvent中,如果设置了mOnClickListener,则onClick会被调用。如果顶层ViewGroup不拦截事件,则事件会传递给它的在点击事件链上的子View,这个时候,子View的dispatchTouchEvent会被调用,到此为止,事件已经从最底层View传递给了上一层View,接下来的行为和其底层View一致,如此循环,完成整个事件派发。另外要说明的是,ViewGroup默认是不拦截点击事件的,其onInterceptTouchEvent返回false。
源码解读:
Code:ViewGroup#dispatchTouchEvent
- @Override
- publicbooleandispatchTouchEvent(MotionEventev){
- if(mInputEventConsistencyVerifier!=null){
- mInputEventConsistencyVerifier.onTouchEvent(ev,1);
- }
- booleanhandled=false;
- if(onFilterTouchEventForSecurity(ev)){
- finalintaction=ev.getAction();
- finalintactionMasked=action&MotionEvent.ACTION_MASK;
- //Handleaninitialdown.
- if(actionMasked==MotionEvent.ACTION_DOWN){
- //Throwawayallpreviousstatewhenstartinganewtouchgesture.
- //Theframeworkmayhavedroppedtheuporcanceleventforthepreviousgesture
- //duetoanappswitch,ANR,orsomeotherstatechange.
- cancelAndClearTouchTargets(ev);
- resetTouchState();
- }
- //Checkforinterception.
- finalbooleanintercepted;
- if(actionMasked==MotionEvent.ACTION_DOWN
- ||mFirstTouchTarget!=null){
- finalbooleandisallowIntercept=(mGroupFlags&FLAG_DISALLOW_INTERCEPT)!=0;
- if(!disallowIntercept){
- //这里判断是否拦截点击事件,如果拦截,则intercepted=true
- intercepted=onInterceptTouchEvent(ev);
- ev.setAction(action);//restoreactionincaseitwaschanged
- }else{
- intercepted=false;
- }
- }else{
- //Therearenotouchtargetsandthisactionisnotaninitialdown
- //sothisviewgroupcontinuestointercepttouches.
- intercepted=true;
- }
- //Checkforcancelation.
- finalbooleancanceled=resetCancelNextUpFlag(this)
- ||actionMasked==MotionEvent.ACTION_CANCEL;
- //Updatelistoftouchtargetsforpointerdown,ifneeded.
- finalbooleansplit=(mGroupFlags&FLAG_SPLIT_MOTION_EVENTS)!=0;
- TouchTargetnewTouchTarget=null;
- booleanalreadyDispatchedToNewTouchTarget=false;
- //这里面一大堆是派发事件到子View,如果intercepted是true,则直接跳过
- if(!canceled&&!intercepted){
- if(actionMasked==MotionEvent.ACTION_DOWN
- ||(split&&actionMasked==MotionEvent.ACTION_POINTER_DOWN)
- ||actionMasked==MotionEvent.ACTION_HOVER_MOVE){
- finalintactionIndex=ev.getActionIndex();//always0fordown
- finalintidBitsToAssign=split?1<<ev.getPointerId(actionIndex)
- :TouchTarget.ALL_POINTER_IDS;
- //Cleanupearliertouchtargetsforthispointeridincasethey
- //havebecomeoutofsync.
- removePointersFromTouchTargets(idBitsToAssign);
- finalintchildrenCount=mChildrenCount;
- if(newTouchTarget==null&&childrenCount!=0){
- finalfloatx=ev.getX(actionIndex);
- finalfloaty=ev.getY(actionIndex);
- //Findachildthatcanreceivetheevent.
- //Scanchildrenfromfronttoback.
- finalView[]children=mChildren;
- finalbooleancustomOrder=isChildrenDrawingOrderEnabled();
- for(inti=childrenCount-1;i>=0;i--){
- finalintchildIndex=customOrder?
- getChildDrawingOrder(childrenCount,i):i;
- finalViewchild=children[childIndex];
- if(!canViewReceivePointerEvents(child)
- ||!isTransformedTouchPointInView(x,y,child,null)){
- continue;
- }
- newTouchTarget=getTouchTarget(child);
- if(newTouchTarget!=null){
- //Childisalreadyreceivingtouchwithinitsbounds.
- //Giveitthenewpointerinadditiontotheonesitishandling.
- newTouchTarget.pointerIdBits|=idBitsToAssign;
- break;
- }
- resetCancelNextUpFlag(child);
- if(dispatchTransformedTouchEvent(ev,false,child,idBitsToAssign)){
- //Childwantstoreceivetouchwithinitsbounds.
- mLastTouchDownTime=ev.getDownTime();
- mLastTouchDownIndex=childIndex;
- mLastTouchDownX=ev.getX();
- mLastTouchDownY=ev.getY();
- //注意下面两句,如果有子View处理了点击事件,则newTouchTarget会被赋值,
- //同时alreadyDispatchedToNewTouchTarget也会为true,这两个变量是直接影响下面的代码逻辑的。
- newTouchTarget=addTouchTarget(child,idBitsToAssign);
- alreadyDispatchedToNewTouchTarget=true;
- break;
- }
- }
- }
- if(newTouchTarget==null&&mFirstTouchTarget!=null){
- //Didnotfindachildtoreceivetheevent.
- //Assignthepointertotheleastrecentlyaddedtarget.
- newTouchTarget=mFirstTouchTarget;
- while(newTouchTarget.next!=null){
- newTouchTarget=newTouchTarget.next;
- }
- newTouchTarget.pointerIdBits|=idBitsToAssign;
- }
- }
- }
- //Dispatchtotouchtargets.
- //这里如果当前ViewGroup拦截了事件,或者其子View的onTouchEvent都返回了false,则事件会由ViewGroup处理
- if(mFirstTouchTarget==null){
- //Notouchtargetssotreatthisasanordinaryview.
- //这里就是ViewGroup对点击事件的处理
- handled=dispatchTransformedTouchEvent(ev,canceled,null,
- TouchTarget.ALL_POINTER_IDS);
- }else{
- //Dispatchtotouchtargets,excludingthenewtouchtargetifwealready
- //dispatchedtoit.Canceltouchtargetsifnecessary.
- TouchTargetpredecessor=null;
- TouchTargettarget=mFirstTouchTarget;
- while(target!=null){
- finalTouchTargetnext=target.next;
- if(alreadyDispatchedToNewTouchTarget&&target==newTouchTarget){
- handled=true;
- }else{
- finalbooleancancelChild=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;
- }
- }
- //Updatelistoftouchtargetsforpointeruporcancel,ifneeded.
- if(canceled
- ||actionMasked==MotionEvent.ACTION_UP
- ||actionMasked==MotionEvent.ACTION_HOVER_MOVE){
- resetTouchState();
- }elseif(split&&actionMasked==MotionEvent.ACTION_POINTER_UP){
- finalintactionIndex=ev.getActionIndex();
- finalintidBitsToRemove=1<<ev.getPointerId(actionIndex);
- removePointersFromTouchTargets(idBitsToRemove);
- }
- }
- if(!handled&&mInputEventConsistencyVerifier!=null){
- mInputEventConsistencyVerifier.onUnhandledEvent(ev,1);
- }
- returnhandled;
- }
下面再看ViewGroup对点击事件的处理
Code:ViewGroup#dispatchTransformedTouchEvent
- /**
- *Transformsamotioneventintothecoordinatespaceofaparticularchildview,
- *filtersoutirrelevantpointerids,andoverridesitsactionifnecessary.
- *Ifchildisnull,assumestheMotionEventwillbesenttothisViewGroupinstead.
- */
- privatebooleandispatchTransformedTouchEvent(MotionEventevent,booleancancel,
- Viewchild,intdesiredPointerIdBits){
- finalbooleanhandled;
- //Cancelingmotionsisaspecialcase.Wedon'tneedtoperformanytransformations
- //orfiltering.Theimportantpartistheaction,notthecontents.
- finalintoldAction=event.getAction();
- if(cancel||oldAction==MotionEvent.ACTION_CANCEL){
- event.setAction(MotionEvent.ACTION_CANCEL);
- if(child==null){
- //这里就是ViewGroup对点击事件的处理,其调用了View的dispatchTouchEvent方法
- handled=super.dispatchTouchEvent(event);
- }else{
- handled=child.dispatchTouchEvent(event);
- }
- event.setAction(oldAction);
- returnhandled;
- }
- //Calculatethenumberofpointerstodeliver.
- finalintoldPointerIdBits=event.getPointerIdBits();
- finalintnewPointerIdBits=oldPointerIdBits&desiredPointerIdBits;
- //Ifforsomereasonweendedupinaninconsistentstatewhereitlookslikewe
- //mightproduceamotioneventwithnopointersinit,thendroptheevent.
- if(newPointerIdBits==0){
- returnfalse;
- }
- //Ifthenumberofpointersisthesameandwedon'tneedtoperformanyfancy
- //irreversibletransformations,thenwecanreusethemotioneventforthis
- //dispatchaslongaswearecarefultorevertanychangeswemake.
- //Otherwiseweneedtomakeacopy.
- finalMotionEventtransformedEvent;
- if(newPointerIdBits==oldPointerIdBits){
- if(child==null||child.hasIdentityMatrix()){
- if(child==null){
- handled=super.dispatchTouchEvent(event);
- }else{
- finalfloatoffsetX=mScrollX-child.mLeft;
- finalfloatoffsetY=mScrollY-child.mTop;
- event.offsetLocation(offsetX,offsetY);
- handled=child.dispatchTouchEvent(event);
- event.offsetLocation(-offsetX,-offsetY);
- }
- returnhandled;
- }
- transformedEvent=MotionEvent.obtain(event);
- }else{
- transformedEvent=event.split(newPointerIdBits);
- }
- //Performanynecessarytransformationsanddispatch.
- if(child==null){
- handled=super.dispatchTouchEvent(transformedEvent);
- }else{
- finalfloatoffsetX=mScrollX-child.mLeft;
- finalfloatoffsetY=mScrollY-child.mTop;
- transformedEvent.offsetLocation(offsetX,offsetY);
- if(!child.hasIdentityMatrix()){
- transformedEvent.transform(child.getInverseMatrix());
- }
- handled=child.dispatchTouchEvent(transformedEvent);
- }
- //Done.
- transformedEvent.recycle();
- returnhandled;
- }
Code:View#dispatchTouchEvent
- /**
- *Passthetouchscreenmotioneventdowntothetargetview,orthis
- *viewifitisthetarget.
- *
- *@parameventThemotioneventtobedispatched.
- *@returnTrueiftheeventwashandledbytheview,falseotherwise.
- */
- publicbooleandispatchTouchEvent(MotionEventevent){
- if(mInputEventConsistencyVerifier!=null){
- mInputEventConsistencyVerifier.onTouchEvent(event,0);
- }
- if(onFilterTouchEventForSecurity(event)){
- //noinspectionSimplifiableIfStatement
- ListenerInfoli=mListenerInfo;
- if(li!=null&&li.mOnTouchListener!=null&&(mViewFlags&ENABLED_MASK)==ENABLED
- &&li.mOnTouchListener.onTouch(this,event)){
- returntrue;
- }
- if(onTouchEvent(event)){
- returntrue;
- }
- }
- if(mInputEventConsistencyVerifier!=null){
- mInputEventConsistencyVerifier.onUnhandledEvent(event,0);
- }
- returnfalse;
- }
3.无人处理的点击事件
如果一个点击事件,子View的onTouchEvent返回了false,则父View的onTouchEvent会被直接调用,以此类推。如果所有的View都不处理,则最终会由Activity来处理,这个时候,Activity的onTouchEvent会被调用。这个问题已经在1和2中做了说明。
相关推荐
由于ListView是上下滑动而item是左右滑动,因此会有滑动冲突,也许你需要了解下android中点击事件的派发流程,请参考Android源码分析-点击事件派发机制。我的解决思路是这样的:重写ListView的onInterceptTouchEvent...
android envent 事件派发机制 源代码
主要为大家详细介绍了Android点击事件派发机制源码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
验证事件派发的demo,可以通过checkbox动态更改是否消费和拦截情况来验证事件派发
通过该框架可优化事件的操作控制,方便不同脚本间事件的调用,要注意监听要在派发事件之前,否则事件无响应。 监听语句:Model.eventManager.addEventListener(枚举类.ToString(), 方法名); 派发语句:Model.event...
行业分类-外包设计-智能快递派发系统及相关方法的说明分析.rar
PYQT5事件派发
电信设备-工单派发专用通信装置及方法.zip
主要为大家详细分析了Android Handler消息派发机制源码,感兴趣的小伙伴们可以参考一下
Android之Input子系统事件分发流程 - CSDN博客原创2013年11月29日 08:49:08Android之Input子系统事件分发流程Andro
主动派发事件总结主动派发事件总结 - snandy -
Flex TitleWindow父子页面的事件派发
Android自定义view:十字按钮本十字按钮可用于智能家电app,通过设置listener就可以监听四个方向的点击事件,同时其button的反应模式如系统给的button一致。在代码中也给出了另外五个普通按钮进行与十字按钮进行效果...
之前看了很多关于Swift派发机制的内容,但感觉没有一篇能够彻底讲清楚这件事情,看完了这篇文章之后我对Swift的派发机制才建立起了初步的认知.一张表总结引用类型,修饰符和它们对于Swift函数派发方式的影响.函数派发...
JavaScript事件派发器,对单页交互应用中组件通信十分有用。个人原创,发现bug可向我github中提issue~
通过广播和事件分发的机制,就显得比较混乱了。 官方在废除的同时,也为我们提供了替换方案,包括实例化一个空的vue实例,使用$emit反应子组件上的状态变化 1.使用$emit触发事件 helloWorld.vue作为父组件,...