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

Android View事件分发机制详解

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

准备了一阵子,一直想写一篇事件分发的文章总结一下,这个知识点实在是太重要了。

一个应用的布局是丰富的,有textview,imageview,button等,这些子view的外层还有viewgroup,如relativelayout,linearlayout。作为一个开发者,我们会思考,当点击一个按钮,android系统是怎样确定我点的就是按钮而不是textview的?然后还正确的响应了按钮的点击事件。内部经过了一系列什么过程呢?

先铺垫一些知识能更加清晰的理解事件分发机制:
1. 通过setcontentview设置的view就是decorview的子view,即decorview是父容器。
2. 点击屏幕时,在手指按下和抬起间,会产生很多事件,down…move…move…up,中间会有很多的move事件,这一系列的事件为一个事件序列
3. dispatchtouchevent方法用于分发事件
4. onintercepttouchevent方法用于拦截事件
5. ontouchevent方法用于处理事件

当一个点击事件(motionevent)产生后,事件最先传递给当前的界面(activity),这点是很好理解的。 activity再将事件传递给窗口(window),然后window将事件传递给顶级view(decorview)。此时,事件已经到达了view了。之后顶级view就会按照事件分发机制去分发事件。具体是这样的:

对于一个根viewgroup来说,点击事件产生后,首先会传递给它,这时它的 dispatchtouchevent 方法就会被调用,如果这个viewgroup的onintercepttouchevent方法返回true就表示它要拦截当前事件,接着事件就会交给这个viewgroup处理,即它的ontouchevent方法就会被调用。如果这个viewgroup的onintercepttouchevent方法返回false,就表示它不拦截当前事件,这时当前事件就会继续传递给它的子元素,接着子元素的dispatchtouchevent方法就会被调用,如此反复直到事件被最终处理。
如果一个view的ontouchevent方法返回false,那么它的父容器的ontouchevent方法会被调用,如果它的父容器的ontouchevent方法还是返回false,那就继续往上抛,当所有的元素都不处理这个事件,那么这个事件会最终传递给activity处理,即activity的ontouchevent方法会被调用。

好了,现在已经铺垫了基础,那么接下来就从源码的角度来分析事件分发机制。

当然是从activity的dispatchtouchevent方法开始分析。源码如下:

public boolean dispatchtouchevent(motionevent ev) {
  if (ev.getaction() == motionevent.action_down) {
    onuserinteraction();
  }
  if (getwindow().superdispatchtouchevent(ev)) {
    return true;
  }
  return ontouchevent(ev);
}

如果当前事件是down的话,就调用onuserinteraction方法,onuserinteraction是一个空方法,我们可以暂时不搭理。然后调用getwindow方法获取到当前activity关联的window,window再调用superdispatchtouchevent方法将事件传入进行分发。
如果superdispatchtouchevent方法返回true的话, view已经处理了事件。整个事件循环结束。如果返回false,没有view处理这个事件。事件往上抛,那就activity自己处理了,即activity的ontouchevent方法会被调用。

因为想要知道事件的整个分发过程,现在关注的是window的superdispatchtouchevent方法,那么就跟进去看看:

public abstract boolean superdispatchtouchevent(motionevent event);

window是一个抽象类,superdispatchtouchevent是一个抽象的方法,那么我们必须要找到window的实现类才行,可是茫茫人海怎么找呢?看到window类的说明就明白了

* <p>the only existing implementation of this abstract class is
 * android.view.phonewindow, which you should instantiate when needing a
 * window.
 */
public abstract class window

意思是window存在唯一的实现是android.view.phonewindow

那么phonewindow里的superdispatchtouchevent方法就是我们要找的信息,如下:

@override
public boolean superdispatchtouchevent(motionevent event) {
  return mdecor.superdispatchtouchevent(event);
}

直接将事件传递给了decorview。这时事件已经是到达view了哦。

那么跟进decorview的superdispatchtouchevent方法看看,如下:

public boolean superdispatchtouchevent(motionevent event) {
  return super.dispatchtouchevent(event);
}

内部调用了父类的dispatchtouchevent方法,那么decorview的父类是什么呢?decorview肯定是view的,那么刚才开篇提到,我们通过setcontentview设置的view,是decorview的子view。那么更加准确的说decorview是一个viewgroup。

private final class decorview extends framelayout implements rootviewsurfacetaker

可以看到decorview是继承自framelayout,framelayout是viewgroup,也就是说decorview是一个viewgroup。

那么现在只需要关注viewgroup的dispatchtouchevent方法。继续前进

viewgroup的事件分发

viewgroup的dispatchtouchevent方法如下:

@override
public boolean dispatchtouchevent(motionevent ev) {

    //代码省略

    // check for interception.
    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;
    }

    //代码省略

    if (!canceled && !intercepted) {

    //代码省略

        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 arraylist<view> preorderedlist = buildorderedchildlist();
          final boolean customorder = preorderedlist == null
              && ischildrendrawingorderenabled();
          final view[] children = mchildren;
          for (int i = childrencount - 1; i >= 0; i--) {
            final int childindex = customorder
                ? getchilddrawingorder(childrencount, i) : i;
            final view child = (preorderedlist == null)
                ? children[childindex] : preorderedlist.get(childindex);

            // if there is a view that has accessibility focus we want it
            // to get the event first and if not handled we will perform a
            // normal dispatch. we may do a double iteration but this is
            // safer given the timeframe.
            if (childwithaccessibilityfocus != null) {
              if (childwithaccessibilityfocus != child) {
                continue;
              }
              childwithaccessibilityfocus = null;
              i = childrencount - 1;
            }

            if (!canviewreceivepointerevents(child)
                || !istransformedtouchpointinview(x, y, child, null)) {
              ev.settargetaccessibilityfocus(false);
              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();
              if (preorderedlist != null) {
                // childindex points into presorted list, find original index
                for (int j = 0; j < childrencount; j++) {
                  if (children[childindex] == mchildren[j]) {
                    mlasttouchdownindex = j;
                    break;
                  }
                }
              } else {
                mlasttouchdownindex = childindex;
              }
              mlasttouchdownx = ev.getx();
              mlasttouchdowny = ev.gety();
              newtouchtarget = addtouchtarget(child, idbitstoassign);
              alreadydispatchedtonewtouchtarget = true;
              break;
            }

            // the accessibility focus didn't handle the event, so clear
            // the flag and do a normal dispatch to all children.
            ev.settargetaccessibilityfocus(false);
          }
          if (preorderedlist != null) preorderedlist.clear();
        }

        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.
    if (mfirsttouchtarget == null) {
      // no touch targets so treat this as an ordinary view.
      handled = dispatchtransformedtouchevent(ev, canceled, null,
          touchtarget.all_pointer_ids);
    }

    //代码省略

    return handled;
}

代码比较长,一点一点分析,先看到一开始的判断

if (actionmasked == motionevent.action_down || mfirsttouchtarget != null)

mfirsttouchtarget != null的意义是viewgroup不拦截事件并将事件交由子元素处理,先这样记着,这从后面的addtouchtarget方法可以得出结论的。

然后又会来到这个if判断。

if (!disallowintercept) {
  intercepted = onintercepttouchevent(ev);
  ev.setaction(action); // restore action in case it was changed
}

那我们看看disallowintercept。而disallowintercept的赋值过程中,有一个 flag_disallow_intercept 标记位

final boolean disallowintercept = (mgroupflags & flag_disallow_intercept) != 0;

这个 flag_disallow_intercept 标记位是可以通过requestdisallowintercepttouchevent方法来设置的。

回到if (!disallowintercept)的判断,进入这个if判断后,就会来到

intercepted = onintercepttouchevent(ev);

调用onintercepttouchevent方法,询问viewgroup是否拦截事件。

读到这里,可以回忆下开篇时铺垫的结论,对于viewgroup,点击事件产生后,首先会传递给它,这时它的 dispatchtouchevent 方法就会被调用,接着会调用它的onintercepttouchevent方法,如果这个viewgroup的onintercepttouchevent方法返回true就表示它要拦截当前事件,接着事件就会交给这个viewgroup处理,即它的ontouchevent方法就会被调用。如果返回false表示不拦截,通常viewgroup也是不拦截事件的。

那现在先分析不拦截的情况,不拦截那就好办了的。经过一系列的判断,就会来到一个for循环遍历。

for (int i = childrencount - 1; i >= 0; i--)

这时viewgroup开始分发传递事件,遍历子元素了。

首先肯定需要过滤掉一些无关点击事件的子元素的,判断子元素是否能够接收点击事件,点击事件的坐标是否落在子元素区域内。

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

如果不能够接收点击事件或者点击事件的坐标没有落在子元素区域,就会跳出当前循环,继续遍历下一个子元素。这下就知道了android系统为什么能够知道点击的是button而不是textview,其实内部就只是做了一个判断嘛。

那么继续分析,子元素符合以上两个条件后,就将事件传递给这个子元素。会来到了这个判断。

if (dispatchtransformedtouchevent(ev, false, child, idbitstoassign))

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

  //代码省略
}

我们看到child!=null的情况,如果子元素不为空,调用子元素的dispatchtouchevent方法继续分发事件,同时返回处理结果布尔值,这时就将事件传递到了子view处理。完成了一轮的事件分发。这个方法先到这里就好。

再看回viewgroup的dispatchtouchevent方法,如果dispatchtransformedtouchevent方法返回true的话,这时事件已经传递给子元素处理,viewgroup已经不管这个事件了。
那么就会进入if语句,最后会来到addtouchtarget方法,这个方法之前是提到过的,用于mfirsttouchtarget标记位的赋值。

那跟进这个方法看看

/**
 * adds a touch target for specified child to the beginning of the list.
 * assumes the target child is not already present.
 */
private touchtarget addtouchtarget(view child, int pointeridbits) {
  touchtarget target = touchtarget.obtain(child, pointeridbits);
  target.next = mfirsttouchtarget;
  mfirsttouchtarget = target;
  return target;
}

其实就是让mfirsttouchtarget指向子元素。

执行完这个addtouchtarget方法后,最终会到break语句,那么就会跳出整个for循环体。viewgroup结束分发过程!

又回到dispatchtransformedtouchevent方法,如果dispatchtransformedtouchevent方法返回false,那么if语句的一大段代码都不执行了,而是回到for循环继续遍历子元素进行分发。如此重复完成事件的传递过程。

现在分析viewgroup拦截事件的情况,如果viewgroup拦截事件的话,那么就会进入以下这个判断

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

注意到dispatchtransformedtouchevent方法的第三个参数child传入的是null,那么就是在dispatchtransformedtouchevent方法中走以下的语句

if (child == null) {
  handled = super.dispatchtouchevent(event);
}

而viewgroup是继承自view的,那么就是viewgroup自己处理事件了。这点我们以下分析了view的事件分发过程就能搞明白了。

以上就是viewgroup的事件分发

那么现在分析已经将事件传递给了子view的情况,view继续调用dispatchtouchevent方法,那我们看看view的dispatchtouchevent方法。

view的事件分发

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 (onfiltertoucheventforsecurity(event)) {
    //noinspection simplifiableifstatement
    listenerinfo li = 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);
  }

  // clean up after nested scrolls if this is the end of a gesture;
  // also cancel it if we tried an action_down but we didn't want the rest
  // of the gesture.
  if (actionmasked == motionevent.action_up ||
      actionmasked == motionevent.action_cancel ||
      (actionmasked == motionevent.action_down && !result)) {
    stopnestedscroll();
  }

  return result;
}

相比于viewgroup的dispatchtouchevent方法,view的dispatchtouchevent方法代码量少了。也相对简单些了。
首先会来到如下判断:

if (li != null && li.montouchlistener != null
    && (mviewflags & enabled_mask) == enabled
    && li.montouchlistener.ontouch(this, event))

li变量在哪里被赋值的呢?通常是在setonclicklistener方法或setontouchlistener方法的时候。

public void setonclicklistener(@nullable onclicklistener l) {
  if (!isclickable()) {
    setclickable(true);
  }
  getlistenerinfo().monclicklistener = l;
}

public void setontouchlistener(ontouchlistener l) {
  getlistenerinfo().montouchlistener = l;
}

而这个getlistenerinfo()如下:

listenerinfo getlistenerinfo() {
  if (mlistenerinfo != null) {
    return mlistenerinfo;
  }
  mlistenerinfo = new listenerinfo();
  return mlistenerinfo;
}

listenerinfo是一个内部类,里面存放的是各种监听事件的引用。

之后会判断如下条件:

li.montouchlistener != null

同理只要setontouchlistener方法设置了,这个引用就不空。这些都是好理解的。那关键到了,

li.montouchlistener.ontouch(this, event)

到了最后一个条件。这个ontouch方法是我们去实现的,它也返回一个布尔值,如果返回true的话,那么就会进入这个if判断最终返回true,跳出整个方法,那么我们可以看到接下来的ontouchevent方法是不会得到执行的。
也就是ontouch的执行在ontouchevent之前。那么如果我们也调用了setonclicklistener方法监听点击事件的话,onclick方法是在哪里调用的呢?我们有理由相信是在ontouchevent方法里调用的。那么就跟进看看。

public boolean ontouchevent(motionevent event) {

  //代码省略

  if (((viewflags & clickable) == clickable ||
      (viewflags & long_clickable) == long_clickable) ||
      (viewflags & context_clickable) == context_clickable) {
    switch (action) {
      case motionevent.action_up:
        boolean prepressed = (mprivateflags & pflag_prepressed) != 0;

  //代码省略

            if (!focustaken) {
              // use a runnable and post this rather than calling
              // performclick directly. this lets other visual state
              // of the view update before click actions start.
              if (mperformclick == null) {
                mperformclick = new performclick();
              }
              if (!post(mperformclick)) {
                performclick();
              }
            }
          }

       //代码省略 

        break;
    }

    return true;
  }

  return false;
}

只要clickable或long_clickable不空, 就会处理这个事件,然而怎么保证clickable或long_clickable不空呢?其实细心的你会发现,刚才上面贴出的setonclicklistener源代码中,会将clickabl属性设置会true

public void setonclicklistener(@nullable onclicklistener l) {
  if (!isclickable()) {
    setclickable(true);
  }
  getlistenerinfo().monclicklistener = l;
}

这样就能进入if判断去处理这个事件了,之后就会来到performclick()方法,应该就是它了,跟进去看看吧。

public boolean performclick() {
  final boolean result;
  final listenerinfo li = mlistenerinfo;
  if (li != null && li.monclicklistener != null) {
    playsoundeffect(soundeffectconstants.click);
    li.monclicklistener.onclick(this);
    result = true;
  } else {
    result = false;
  }

  sendaccessibilityevent(accessibilityevent.type_view_clicked);
  return result;
}

熟悉接口回调机制的你,一定也读懂了performclick()方法的源码,

li.monclicklistener.onclick(this);

是在执行这行代码时,调用了我们熟悉的onclick方法

以上就是view的事件分发机制。

此时已经将事件分发机制分析完了,由于我的技术的原因,驾驭的不好,有些关键点还是没分析清楚,但我相信学完了这篇文章能让我和你都对事件分发机制的实现有一个大致的认识,有这个已经可以了,之后还可以一点点去强化锻炼,深入理解事件分发机制。才能为自定义控件铺垫良好的基础。

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

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

相关文章:

验证码:
移动技术网