View 事件分发 拦截

2020-10-13  本文已影响0人  米奇小林

贯穿整个事件围绕着 dispatchTouchEvent()、onInterceptTouchEvent()和onTouchEvent()方法。

1.dispatchTouchEvent是处理触摸事件分发,事件(多数情况)是从Activity的dispatchTouchEvent开始的,执行super.dispatchTouchEvent(ev),事件向下分发。(Activity dispatchTouchEvent 方法 实质上是 DecorView 的)

2.onInterceptTouchEvent是ViewGroup提供的方法,默认返回false,返回true表示拦截。

3.onTouchEvent是View中提供的方法,ViewGroup也有这个方法,view中不提供onInterceptTouchEvent。view中默认返回true,表示消费了这个事件。

1.在Activity里,有两个回调函数

public boolean dispatchTouchEvent(MotionEvent ev);
public boolean onTouchEvent(MotionEvent ev);

2.ViewGroup里,有三个回调函数

public boolean dispatchTouchEvent(MotionEvent ev);  
public boolean onInterceptTouchEvent(MotionEvent ev);  
public boolean onTouchEvent(MotionEvent ev);

3.View里,有两个回调函数

public boolean dispatchTouchEvent(MotionEvent ev);
public boolean onTouchEvent(MotionEvent ev);

Android中默认情况下事件传递是由最终的view的接收到,传递过程是从父布局到子布局,也就是从Activity到ViewGroup到View的过程,默认情况,ViewGroup起到的是透传作用。大部分情况如以下图片:

事件传递.jpg

1.ACTION_DOWN都不消费:

1.jpg

2.ACTION_DOWN最终被View消费

2.jpg

3.ACTION_MOVE和UP在不被拦截的情况下都会传递到view

3.jpg

4.事件被 ViewGroup 消费,view接收到后续事件

4.jpg

5.ACTION_DOWN一开始就被上层拦截

5.jpg

重点描述一下 dispatchTouchEvent() 返回值 事件分发

1.false 代表不分发事件,事件到此处结束。(后续事件触发,如 只接收到DOWN 事件 后续的 move up 不再处理)

2.true 代表此刻事件分发成功,效果与 false 类似,都代表不再向下传递。

3.super.dispatchTouchEvent(event) 交由child 继续分发。

疑点

ACTION_CANCEL 事件 在做实验时没有捕捉到

上一篇下一篇

猜你喜欢

热点阅读