欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android点击事件派发机制源码分析

程序员文章站 2024-03-06 16:34:50
概述  一直想写篇关于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

   /**
   * 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, 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
  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。 

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, child, 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处理。 

3.无人处理的点击事件 

如果一个点击事件,子view的ontouchevent返回了false,则父view的ontouchevent会被直接调用,以此类推。如果所有的view都不处理,则最终会由activity来处理,这个时候,activity的ontouchevent会被调用。这个问题已经在1和2中做了说明。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。