@H_404_1@概述
一直想写篇关于AndroID事件派发机制的文章,却一直没写,这两天刚好是周末,有时间了,想想写一篇吧,不然总是只停留在会用的层次上但是无法了解其内部机制。我用的是4.4源码,打开看看,挺复杂的,尤其是事件是怎么从Activity派发出来的,太费解了。了解windows消息机制的人会发现,觉得AndroID的事件派发机制和windows的消息派发机制挺像的,其实这是一种典型的消息“冒泡”机制,很多平台采用这个机制,消息最先到达最底层VIEw,然后它先进行判断是不是它所需要的,否则就将消息传递给它的子VIEw,这样一来,消息就从水底的气泡一样向上浮了一点距离,以此类推,气泡达到顶部和空气接触,破了(消息被处理了),当然也有气泡浮出到顶层了,还没破(消息无人处理),这个消息将由系统来处理,对于AndroID来说,会由Activity来处理。
@H_404_1@AndroID点击事件的派发机制
@H_404_1@1. 从Activity传递到底层VIEw
点击事件用MotionEvent来表示,当一个点击 *** 作发生时,事件最先传递给当前Activity,由Activity的dispatchtouchEvent来进行事件派发,具体的工作是由Activity内部的Window来完成的,Window会将事件传递给decor vIEw,decor vIEw一般就是当前界面的底层容器(即setContentVIEw所设置的VIEw的父容器),通过Activity.getwindow.getDecorVIEw()可以获得。另外,看下面代码的的时候,主要看我注释的地方,代码很多很复杂,我无法一一说明,但是我注释的地方都是关键点,是博主仔细读代码总结出来的。
源码解读:
事件是由哪里传递给Activity的,这个我还不清楚,但是不要紧,我们从activity开始分析,已经足够我们了解它的内部实现了。
Code:Activity#dispatchtouchEvent
/** * Called to process touch screen events. You can overrIDe this to * intercept all touch screen events before they are dispatched to the * window. Be sure to call this implementation for touch screen events * that should be handled normally. * * @param ev The touch screen event. * * @return boolean Return true if this event was consumed. */ public boolean dispatchtouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { //这个函数其实是个空函数,啥也没干,如果你没重写的话,不用关心 onUserInteraction(); } //这里事件开始交给Activity所附属的Window进行派发,如果返回true,整个事件循环就结束了 //返回false意味着事件没人处理,所有人的ontouchEvent都返回了false,那么Activity就要来做最后的收场。 if (getwindow().superdispatchtouchEvent(ev)) { return true; } //这里,Activity来收场了,Activity的ontouchEvent被调用 return ontouchEvent(ev); }
Window是如何将事件传递给VIEwGroup的
Code:Window#superdispatchtouchEvent
/** * Used by custom windows,such as Dialog,to pass the touch screen event * further down the vIEw hIErarchy. Application developers should * not need to implement or call this. * */ public abstract boolean superdispatchtouchEvent(MotionEvent event);
这竟然是一个抽象函数,还注明了应用开发者不要实现它或者调用它,这是什么情况?再看看如下类的说明,大意是说:这个类可以控制顶级VIEw的外观和行为策略,而且还说这个类的唯一一个实现位于androID.policy.PhoneWindow,当你要实例化这个Window类的时候,你并不知道它的细节,因为这个类会被重构,只有一个工厂方法可以使用。好吧,还是很模糊啊,不太懂,不过我们可以看一下androID.policy.PhoneWindow这个类,尽管实例化的时候此类会被重构,但是重构而已,功能是类似的。
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,@R_419_5979@ 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 public boolean superdispatchtouchEvent(MotionEvent event) { return mDecor.superdispatchtouchEvent(event); }这个逻辑很清晰了,PhoneWindow将事件传递给DecorVIEw了,这个DecorVIEw是啥呢,请看下面 private final class DecorVIEw extends FrameLayout implements RootVIEwSurfaceTaker // This is the top-level vIEw of the window,containing the window decor. private DecorVIEw mDecor; @OverrIDe public final VIEw getDecorVIEw() { if (mDecor == null) { installDecor(); } return mDecor; }
顺便说一下,平时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。
@H_404_1@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 public boolean dispatchtouchEvent(MotionEvent ev) { if (minputEventConsistencyVerifIEr != null) { minputEventConsistencyVerifIEr.ontouchEvent(ev,1); } boolean handled = false; if (onFiltertouchEventForSecurity(ev)) { final int action = ev.getAction(); final int actionMasked = action & MotionEvent.ACTION_MASK; // 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(); } // Check for interception. final boolean intercepted; if (actionMasked == MotionEvent.ACTION_DOWN || mFirsttouchTarget != null) { final boolean disallowIntercept = (mGroupFlags & FLAG_disALLOW_INTERCEPT) != 0; if (!disallowIntercept) { //这里判断是否拦截点击事件,如果拦截,则intercepted=true 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; } // Check for cancelation. final boolean canceled = resetCancelNextUpFlag(this) || actionMasked == MotionEvent.ACTION_CANCEL; // Update List of touch targets for pointer down,if needed. final boolean split = (mGroupFlags & FLAG_SPliT_MOTION_EVENTS) != 0; touchTarget newtouchTarget = null; boolean alreadydispatchedToNewtouchTarget = false; //这里面一大堆是派发事件到子VIEw,如果intercepted是true,则直接跳过 if (!canceled && !intercepted) { if (actionMasked == MotionEvent.ACTION_DOWN || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN) || actionMasked == MotionEvent.ACTION_HOVER_MOVE) { final int actionIndex = ev.getActionIndex(); // always 0 for down final int IDBitsToAssign = split ? 1 << ev.getPointerID(actionIndex) : touchTarget.ALL_POINTER_IDS; // Clean up earlIEr touch targets for this pointer ID in case they // have become out of sync. removePointersFromtouchTargets(IDBitsToAssign); final int childrenCount = mChildrenCount; if (newtouchTarget == null && childrenCount != 0) { final float x = ev.getX(actionIndex); final float y = ev.getY(actionIndex); // Find a child that can receive the event. // Scan children from front to back. final VIEw[] children = mChildren; final boolean customOrder = isChildrenDrawingOrderEnabled(); for (int i = childrenCount - 1; i >= 0; i--) { final int childindex = customOrder ? getChildDrawingOrder(childrenCount,i) : i; final VIEw child = children[childindex]; if (!canVIEwReceivePointerEvents(child) || !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,IDBitsToAssign)) { // Child wants to receive touch within its bounds. 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) { // DID not find a child to receive the event. // Assign the pointer to the least recently added target. newtouchTarget = mFirsttouchTarget; while (newtouchTarget.next != null) { newtouchTarget = newtouchTarget.next; } newtouchTarget.pointerIDBits |= IDBitsToAssign; } } } // dispatch to touch targets. //这里如果当前VIEwGroup拦截了事件,或者其子VIEw的ontouchEvent都返回了false,则事件会由VIEwGroup处理 if (mFirsttouchTarget == null) { // No touch targets so treat this as an ordinary vIEw. //这里就是VIEwGroup对点击事件的处理 handled = dispatchtransformedtouchEvent(ev,canceled,null,touchTarget.ALL_POINTER_IDS); } else { // dispatch to touch targets,excluding the new touch target if we already // dispatched to it. Cancel touch targets if necessary. 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; } } // Update List of touch targets for pointer up or cancel,if needed. if (canceled || actionMasked == MotionEvent.ACTION_UP || actionMasked == MotionEvent.ACTION_HOVER_MOVE) { resettouchState(); } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) { final int actionIndex = ev.getActionIndex(); final int IDBitsToRemove = 1 << ev.getPointerID(actionIndex); removePointersFromtouchTargets(IDBitsToRemove); } } if (!handled && minputEventConsistencyVerifIEr != null) { minputEventConsistencyVerifIEr.onUnhandledEvent(ev,1); } return handled; }
下面再看VIEwGroup对点击事件的处理
Code:VIEwGroup#dispatchtransformedtouchEvent
/** * transforms a motion event into the coordinate space of a particular child vIEw,* filters out irrelevant pointer IDs,and overrIDes its action if necessary. * If child is null,assumes the MotionEvent will be sent to this VIEwGroup instead. */ private boolean dispatchtransformedtouchEvent(MotionEvent event,boolean cancel,VIEw child,int desiredPointerIDBits) { final boolean handled; // Canceling motions is a special case. We don't need to perform any transformations // or filtering. The important part is the action,not the contents. final int oldAction = 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); return handled; } // Calculate the number of pointers to deliver. final int oldPointerIDBits = event.getPointerIDBits(); final int newPointerIDBits = oldPointerIDBits & desiredPointerIDBits; // If for some reason we ended up in an inconsistent state where it looks like we // might produce a motion event with no pointers in it,then drop the event. if (newPointerIDBits == 0) { return false; } // If the number of pointers is the same and we don't need to perform any fancy // irreversible transformations,then we can reuse the motion event for this // dispatch as long as we are careful to revert any changes we make. // Otherwise we need to make a copy. final MotionEvent transformedEvent; if (newPointerIDBits == oldPointerIDBits) { if (child == null || child.hasIDentityMatrix()) { if (child == null) { handled = super.dispatchtouchEvent(event); } else { final float offsetX = mScrollX - child.mleft; final float offsetY = mScrollY - child.mtop; event.offsetLocation(offsetX,offsetY); handled = child.dispatchtouchEvent(event); event.offsetLocation(-offsetX,-offsetY); } return handled; } transformedEvent = MotionEvent.obtain(event); } else { transformedEvent = event.split(newPointerIDBits); } // 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; }
再看
Code:VIEw#dispatchtouchEvent
/** * Pass the touch screen motion event down to the target vIEw,or this * vIEw if it is the target. * * @param event The motion event to be dispatched. * @return True if the event was handled by the vIEw,false otherwise. */ public boolean dispatchtouchEvent(MotionEvent event) { if (minputEventConsistencyVerifIEr != null) { minputEventConsistencyVerifIEr.ontouchEvent(event,0); } if (onFiltertouchEventForSecurity(event)) { //noinspection SimplifiableIfStatement ListenerInfo li = mListenerInfo; if (li != null && li.mOntouchListener != null && (mVIEwFlags & ENABLED_MASK) == ENABLED && li.mOntouchListener.ontouch(this,event)) { return true; } if (ontouchEvent(event)) { return true; } } if (minputEventConsistencyVerifIEr != null) { minputEventConsistencyVerifIEr.onUnhandledEvent(event,0); } return false; }
这段代码比较简单,VIEw对事件的处理是这样的:如果设置了OntouchListener就调用ontouch,否则就直接调用ontouchEvent,而onClick是在ontouchEvent内部通过performClick触发的。简单来说,事件如果被VIEwGroup拦截或者子VIEw的ontouchEvent都返回了false,则事件最终由VIEwGroup处理。
@H_404_1@3.无人处理的点击事件
如果一个点击事件,子VIEw的ontouchEvent返回了false,则父VIEw的ontouchEvent会被直接调用,以此类推。如果所有的VIEw都不处理,则最终会由Activity来处理,这个时候,Activity的ontouchEvent会被调用。这个问题已经在1和2中做了说明。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
总结以上是内存溢出为你收集整理的Android点击事件派发机制源码分析全部内容,希望文章能够帮你解决Android点击事件派发机制源码分析所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)