Android 事件分发 onInterceptTouchEvent

Android中,事件类型为MotionEvent,一次完整的触摸事件由一个ACTION_DOWN,多个ACTION_MOVE以及一个ACTION_UP组成。

事件分发主要的对象包括Activity,ViewGroup以及View三个层级。事件分发的流程是

Android事件分发主要涉及方法为:

onTouchEvent()

dispatchEvent()

onInterceptTouchEvent()

Android事件分发机制详解:史上最全面、最易懂_android 事件分发-CSDN博客

事件分发中的基本流程,包括onTouchEvent,onTouch,onClick已经在这一链接中详细讲解了,补充一点,onInterceptTouchEvent的相关知识:

public boolean onInterceptTouchEvent (MotionEvent ev)

Implement this methodto intercept all touch screen motion events. This allows you to watch events asthey are dispatched to your children, and take ownership of the current gestureat any point.

Using this functiontakes some care, as it has a fairly complicated interaction withView.onTouchEvent(MotionEvent),and using it requires implementing that method as well as this one in thecorrect way. 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 actionACTION_CANCEL, and all further events will be delivered to your onTouchEvent() method and no longer appear here.

举个例子:

一次完整的触摸事件由一个ACTION_DOWN,多个ACTION_MOVE以及一个ACTION_UP组成,View A在消费当前触摸事件,从ACTION_DOWN事件开始,后续的事件全部都会分发到View A中,在onTouchEvent中被消费,而在ACTION_MOVE的过程中,由于触摸事件坐标的不断变化,在某一个ACTION_MOVE事件被拦截,因此后续事件不再会分发到VIew A中,那VIew A将没有办法接收到一个完整的触摸事件,Android在这种情况下,会将最后一个事件中的ACTION_MOVE替换为ACTION_CANCEL,the target view will receive the same event but with the actionACTION_CANCEL,保证VIew A接收到一个完整的触摸事件。

因此,拦截的处理最好在View A的上层View 的  onInterceptTouchEvent()进行处理,而不是View A的 onTouchEvent()中。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值