研究Android事件分发笔记

开发中总是遇到事件冲突处理不好的问题,所以想从源码好好研究下Android中事件分发机制。
借鉴:http://www.cnblogs.com/mengdd/p/3394345.html
Android中提供了ViewGroup、View、Activity三个层次的Touch事件处理。
  处理过程是按照Touch事件从上到下传递,再按照是否消费的返回值,从下到上返回,即如果View的onTouchEvent返回false,将会向上传给它的parent的ViewGroup,如果ViewGroup不处理,将会一直向上返回到Activity。
  即隧道式向下分发,然后冒泡式向上处理。

首先看Activity中的dispatchTouchEvent方法:

onUserInteraction方法在action_down时会调用,是个空实现,可以重写这个方法就能知道在Activity运行时,用户以某种方式与设备互动。

    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

处理屏幕触摸事件,你可以覆写这个方法来截获所有的触摸屏幕事件,是在它们分发到窗口之前截获。
对于要正常处理的触摸屏幕事件,要确认调用这个实现。
返回值为true的时候,表明这个事件被消费

可以看出Activity的事件分发方法最终调了onTouchEvent(ev)方法,代码如下:

/**
* Called when a touch screen event was not handled by any of the views
* under it.  This is most useful to process touch events that happen
* outside of your window bounds, where there is no view to receive it.
* 
* @param event The touch screen event being processed.
* 
* @return Return true if you have consumed the event, false if you haven't. 
* The default implementation always returns false.
*/
public boolean onTouchEvent(MotionEvent event) {
   if (mWindow.shouldCloseOnTouch(this, event)) {
          finish();
          return true;
   }

   return false;
}

如果一个屏幕触摸事件没有被这个Activity下的任何View所处理,Activity的onTouchEvent将会调用。
  这对于处理window边界之外的Touch事件非常有用,因为通常是没有View会接收到它们的。
  返回值为true表明你已经消费了这个事件,false则表示没有消费,默认实现中返回false。
可以看出Activity中onTouchEvent返回false,没有做判断,也没有做拦截处理,直接传给子类。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章