当前位置: 移动技术网 > 移动技术>移动开发>Android > Android View 事件分发机制详解

Android View 事件分发机制详解

2019年07月24日  | 移动技术网移动技术  | 我要评论

android开发,触控无处不在。对于一些 不咋看源码的同学来说,多少对这块都会有一些疑惑。view事件的分发机制,不仅在做业务需求中会碰到这些问题,在一些面试笔试题中也常有人问,可谓是老生常谈了。我以前也看过很多人写的这方面的文章,不是说的太啰嗦就是太模糊,还有一些在细节上写的也有争议,故再次重新整理一下这块内容,十分钟让你搞明白view事件的分发机制。

说白了这些触控的事件分发机制就是弄清楚三个方法,dispatchtouchevent(),onintercepttouchevent(),ontouchevent(),和这三个方法与n个viewgroup和view堆叠在一起的问题,再复杂的结构都能拆分成1个viewgroup+1个view。

其实viewgroup和view都是大同小异,view只是没有了子容器,自然不存在拦截问题,dispatch也很简单,所以弄明白了viewgroup其实就懂的差不多了。

三个关键方法

public boolean dispatchtouchevent(motionevent ev)

view/viewgroup处理事件分发的发起者,view/viewgroup接收到触控事件最先调起的就是这个方法,然后在该方法中判断是否处理拦截或是将事件分发给子容器

public boolean onintercepttouchevent(motionevent ev)

viewgroup专用,通过该方法可以达到控件事件的分发方向,一般可以在该方法中判断将事件给viewgroup独吞或是它继续传递给子容器,是处理事件冲突的最佳地点

public boolean ontouchevent(motionevent event)

触控事件的真正处理者,最后每个事件都会在这里被处理

核心问题

时间分发机制的难点在哪,我觉得难的地方以下几点:三个方法调用规则,确定处理事件的对象以及事件冲突的解决方法。

事件传递规则

一般一次点击会有一系列的motionevent,可以简单分为:down->move->….->move->up,当一次event分发到viewgroup时,上述三个方法之间的 viewgroup中调用顺序可以用一段简单代码表示

motionevent ev;//down or move or up or others...
viewgroup.dispatchtouchevent(ev);

public boolean dispatchtouchevent(motionevent ev){
 boolean isconsumed = false;
  if(onintercepttouchevent(ev)){
   iscousumed = this.ontouchevent(ev);
  }else{
   isconsumed = childview.dispatchtouchevent(ev);
  }
  return isconsumed;
}

返回结果true表示事件被处理了,返回false表示没有处理。上面的代码通俗易懂,看起来也很简单,一句话就能概括,viewgroup收到事件后调用dispatch,在dispatch中先检查是否要拦截,若拦截则viewgroup吃掉事件,否则交给有处理能力的子容器处理。

不过,简单归简单,写成这样只是为了方便理解,viewgroup的事件处理流程当然没这么简单,这里忽略了很多细节问题,接下来继续补充。回到上面说的,一系列事件我们经常处理的一般都是一个down,多个move和一个up,光靠上面的伪代码是没办法把这些问题都给完美解决,直接来看viewgroup的dispatchtouchevent。

onintercepttouchevent调用条件

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;
}

解释一下上面的代码,看起来好像很简单,但真的很简单吗。。在解释之前先说一下intercepted代表的含义,intercepted == false表示父容器viewgroup暂时不拦截事件,事件有机会传给子view处理,返回true表示父容器直接拦截了该系列事件,后续不会再传递给子view了。子view想获取事件只能让该值为false

onintercepttouchevent调用返回false(返回false才能传递给子view,对应到上面伪代码的else中的内容,叫事件传递到子容器需要满足的内容更好理解一些)需要满足两个条件中的任意一个就有可能触发(当然只是有可能):

一个是在down的时候,另一个就是mfirsttouchtarget!=null,那mfirsttouchtarget何时不为空,有兴趣的同学可以看viewgroup中的addtouchtarget这个方法的调用时机,mfirsttouchtarget就是在这里赋值的,源码太长我就不贴了。

mfirsttouchtarget是用来保存viewgroup中消费了action_down事件的子view,即在上面伪代码中child.dispatchtouchevent(ev)在action_down的时候返回true的view,只要有子view的dispatch在action_down返回true,就不会为null(这个赋值过程只发生在action_down里,如果子viewaction__down不给它赋值后面序列的事件就不会再),反之,若无子view处理,该对象即为null。当然,满足了上述两个条件还不行,必须还要满足!disallowintercept。

disallowintercept这个变量很有意思,它的值主要受flag_disallow_intercept这个标记影响,这个值可以被viewgroup的子view设置,viewgroup的子view如果调用了requestdisallowintercepttouchevent这个方法,会改变flag_disallow_intercept,导致disallowintercept这个值就是ture了,这种情况会跳过intercept,导致拦截失效。

但这事还没了,flag_disallow_intercept这个标记有一个重置的机制,查看viewgroup源码可以看到,在处理motionevent.action_down的时候会重置这个标记导致disallowintercept失效,是不是丧心病狂,上面的一段这么简单的代码有这么多幺蛾子,这里还能得到一个结论,action_down的时候肯定可以执行onintercepttouchevent的。

所以拦截的intercepted很重要,能影响到底是让viewgroup还子view处理这个事件。

上面的两个有可能触发拦截的条件说完了,那么当两个条件都不满足的话就不会再调用拦截了(拦截很重要,一般viewgroup都返回false这样能把事件传递给子view,如果在action_down时不能走到onintercepttouchevent并返回false告诉viewgroup不要拦截,则事件再也不能传给子view了,所以拦截一般都是要走到的,而且一般都是返回false这样能让子view有机会处理),这种情况一般都是在action_down处理完之后没有子view当接盘侠消费action_down以及后续事件,从上面的伪代码可以看出来,这时候viewgroup自己就很被动了,需要自己来调用ontouchevent来处理,这锅就自己背了。

再继续说一下mfirsttouchtarget和intercepted是怎么影响事件方向的。看源码:

if (!canceled && !intercepted) {
....
if (actionmasked == motionevent.action_down
            || (split && actionmasked == motionevent.action_pointer_down)
            || actionmasked == motionevent.action_hover_move) {
 ....
 for(child : childlist){
   if(!child satisfied condition....){
     continue;
   }
   newtouchtarget = addtouchtarget(child, idbitstoassign);//在这里给mfirsttouchtarget赋值
 }

 }
}

可以在这里看到intercepted为false在action_down里才能给上面说过的mfirsttouchtarget赋值,只有mfirsttouchtarget不为空才能让后续事件传递给子view,否则根据上上面说的代码后续事件只能给父容器处理了。

mfirsttouchtarget就是我们后续事件传递的对象,很容易理解,如果在action_down中没有确定这个对象,则后续事件不知道传递给谁自然就交给父容器viewgroup处理了,真正处理事件传递的方法是dispatchtransformedtouchevent,再看源码:

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) {
        handled = super.dispatchtouchevent(event);
      } else {
        handled = child.dispatchtouchevent(event);
      }
      event.setaction(oldaction);
      return handled;
    }

}

看到没,只要参数里传的child为空,则viewgroup调用super.dispatchtouchevent(event),super是谁,viewgroup继承自view,当然是view咯,view的dispatch调用的谁?当然是自己的ontouchevent(后面会说),所以这个最后还是调用了viewgroup自己的ontouchevent。

那么当child!=null的时候呢,调用的是child的dispatchtouchevent(event),如果child可能是view也可能是viewgroup,如果是viewgroup则继续按照上面的伪代码执行事件分发,如果也是view则调用自己的ontouchevent。

所以,说到底事件到底给谁处理,还是和传进来的child有关,那这个方法在哪里调用的呢,继续看:

if (mfirsttouchtarget == null) {
        // no touch targets so treat this as an ordinary view.
        handled = dispatchtransformedtouchevent(ev, canceled, null,
            touchtarget.all_pointer_ids);
      } else {
     ...
     dispatchtransformedtouchevent(ev, cancelchild,
                target.child, target.pointeridbits)
   }

这就是为什么mfirsttouchtarget能影响事件分发的方向的原因。就这样,整个伪代码的流程是不是很清楚了。

这里需要多说两句,在上上面代码流程中,intercepted决定了这个事件会不会调用viewgroup的ontouchevent,当intercepted为true则后续流程会调用viewgroup的ontouchevent,仔细看上面的代码能发现,只有两种情况为ture:一是调用了intercepttouchevent把事件拦截下来,另一个就是没有一个子view能够消费actiondown。只有这两种情况父容器viewgroup才会自己处理
那么问题来了,思考一个问题:如果子view处理了action_down但后续事件都返回false,这些没有被处理的事件最后传给谁处理了?各位思考之,后面再说这个问题。

孩子是谁的

继续来扩展我们的伪代码,拦截条件判断完之后,决定把事件继续传递给子view的时候,会调用childview.dispatchtouchevent(ev),问题来了,child是哪来的,继续看源码

if (!canviewreceivepointerevents(child)
  || !istransformedtouchpointinview(x, y, child, null)) {
   ev.settargetaccessibilityfocus(false);
   continue;
}

viewgroup通过判断所有的子view是否可见是否在播放动画和是否在点击范围内来决定它是否能够有资格接受事件。只有满足条件的child才能够调用dispatch。

再看伪代码,最后dispatch返回viewgroup的isconsumed,若isconsume == true,说明viewgroup处理了这个点击事件(viewgroup自身或者子view处理的),并且这个系列的点击事件会继续传到这个viewgroup来处理,若isconsume == false(action_down时),viewgroup没办法处理这个点击事件,那么这个系类的点击事件就和该viewgroup无缘了。会把这个事件上抛给自己的父容器或者activity处理。

伪代码说完了,viewgroup的事件传递规则也就差不多说完了,这么看是不是很简单了。view相对于viewgroup来说就更简单了,没有拦截方法,dispatch基本上是直接调用了自身的ontouchevent,处理起来一点难度都木有呀。

一些没说到但也很重要的点

上面解释的东西都很简单,是从一个viewgroup+一个view开始的,事件分发的执行者是viewgroup,子容器也只有一个view,但实际开发中当然没这么简单,不过不要怕,再复杂的情况也能够拆分成这种模式的,只不过层次多了一些递归复杂了一些而已,原理还是一样的。

顺带补充几点:

从用户点击屏幕开始触发一个系列的点击事件时,事件真正的传递流程是:activity(phonewindow)->decorview->viewgroup->view,在到达viewgroup之前还有一个decorview,事件是从activity传过来的,但这些东西其实和viewgroup的原理是一样的,activity能看做一个大的viewgroup,当它的decorview包含的所有子view没有人能够消耗事件的时候(这样说有漏洞,大家懂我的意思就行了)最后还是会交给activity处理。

事件冲突解决可以按照上面的原理在几个point中进行处理。最容易想到的处理的时机是在onintercepttouchevent里,比如当一个竖直方向滑动的viewgroup里嵌套一个横向滑动的viewgroup,可以在这里的action_move里来判断后续事件应该传递给谁处理,当然,也可以根据上面说的标记位flag_disallow_intercept配合子view的dispatchtouchevent来控制事件的流向,这都是比较容易想到的,不过看过别的大神,通过分享motionevent的方法来控制事件的流向,即在父容器中保存motionevent并在适当的时机传入子view自定义的事件处理方法来分享事件,也是可行的。

任何view只要拒绝了一系列事件中的action_down(返回false),则后续事件都不会再传递过来了。但如果拒绝了其他的事件,后续事件还是可以传过来的,比如view某次action_move没处理,这个没处理的事件最后会被activity消耗掉(而不是view的父容器),但后续的事件还是会继续传给该view。

合理的利用action_cancel能够控制一个系列事件的生命周期,让事件处理更加灵活。

理解事件分发的机制只要明白上面的原理基本就够用了,github上很多牛逼的大神写的各种炫酷的自定义控件的事分发根据这些也能够看明白,当然还有很多扩展的东西和更深入的内容由于篇幅的关系在这里就不罗嗦了,更重要的还是去看源码吧。
最后送各位一句经典:纸上得来终觉浅,绝知此事要躬行!

以上就是对android view事件分发机制的资料整理,后续继续补充相关资料,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网