Android中的事件传递

来源:互联网 发布:fakin it 编辑:程序博客网 时间:2024/04/23 15:11

     前段时间项目中用到了一个九宫格按钮拖动效果的需求,当时写的比较乱,现在有看了一下onInterceptTouchEvent和onTouchEvent()的传递过程,这里做下记录,首先看api文档中对onInterceptTouchEvent()的描述

    Events will be received in the following order:

  1. You will receive the down event here.
  2. The down event will be handled either by a child of this view group, or given to your own onTouchEvent() method to handle; this means you should implement onTouchEvent() to return true, so you will continue to see the rest of the gesture (instead of looking for a parent view to handle it). Also, by returning true from onTouchEvent(), you will not receive any following events in onInterceptTouchEvent() and all touch processing must happen in onTouchEvent() like normal.
  3. For as long as you return false from this function, each following event (up to and including the final up) will be delivered first here and then to the target's onTouchEvent().
  4. If you return true from here, you will not receive any following events: the target view will receive the same event but with the action MotionEvent.ACTION_CANCEL, and all further events will be delivered to your onTouchEvent() method and no longer appear here.

   这里说下我的理解

   首先onInterceptTouchEvent()是负责事件往下级(子view)传递的,返回true就不往下传递,而是交由自己的onTouchEvent()方法处理。而onTouchEvent()是决定是否向上级(父view)传递的,返回true就不往上传递。

   其次,根据上面第2点所说的,就是如果本view中的onInterceptTouchEvent()返回的是true,那么事件是肯定不会往下传递的,同时,以后传进来的MotionEvent对象是不会再出现在onInterceptTouchEvent()方法中,而是直接交由onTouchEvent()方法处理的。这里可以举个例子,ViewGroup A中包含了ViewGroup B,A中的onInterceptTouchEvent返回false,是其事件可以传递到B,B中的onInterceptTouchEvent和onTouchEvent都返回了false,不过A中的onTouchEvent返回了true,那么在ACTION_DOWN之后的所有事件就都交给A的onTouchEvent处理了,与B无关了。

   最后,关于第4点,我试了半天都没实现。只能以后遇到时再说了。。

原创粉丝点击