事件分发设计的几个函数:
public boolean dispatchTouchEvent(MotionEvent ev)
public boolean onInterceptTouchEvent(MotionEvent ev)
public boolean onTouchEvent(MotionEvent event)
MotionEvent 的几个取值
/**
* Constant for {@link #getActionMasked}: A pressed gesture has started, the
* motion contains the initial starting location.
* <p>
* This is also a good time to check the button state to distinguish
* secondary and tertiary button clicks and handle them appropriately.
* Use {@link #getButtonState} to retrieve the button state.
* </p>
*/
public static final int ACTION_DOWN = 0;
/**
* Constant for {@link #getActionMasked}: A pressed gesture has finished, the
* motion contains the final release location as well as any intermediate
* points since the last down or move event.
*/
public static final int ACTION_UP = 1;
/**
* Constant for {@link #getActionMasked}: A change has happened during a
* press gesture (between {@link #ACTION_DOWN} and {@link #ACTION_UP}).
* The motion contains the most recent point, as well as any intermediate
* points since the last down or move event.
*/
public static final int ACTION_MOVE = 2;
/**
* Constant for {@link #getActionMasked}: The current gesture has been aborted.
* You will not receive any more points in it. You should treat this as
* an up event, but not perform any action that you normally would.
*/
public static final int ACTION_CANCEL = 3;
1、Activity
2、ViewGroup(一组view的集合)
3、View
三者之间的关系:
事件传递过程:Activity =》ViewGroup =》View
dispatchTouchEvent返回值
三种返回值:
return super.onTouchEvent(event);
return true;
return false;
1、不包含onInterceptTouchEvent函数的消息传递流程
正常的消息传递流程:
(1)在dispatchTouchEvent函数中返回true拦截
在某一个传递对象中返回了true,即将此事件消费不会往下继续传递,比方说在Activity 中返回true拦截,即消费了该消息,消息不会传递到下一层view了。
(2)在dispatchTouchEvent函数中返回false拦截
当返回false进行拦截,消息不会继续在dispatchTouchEvent这条线上传递;但是消息不会停止传递,而是继续向父控件的onTouchEvent函数进行回传。比方说在某一个TextView的dispatchTouchEvent函数中返回false,则会将消息回传给其父控件的onTouchEvent函数。
(3)在onTouchEvent函数中拦截ACTION_DOWN消息
无论在哪个控件的onTouchEvent函数中拦截消息,消息都会停止传递,后面的父控件不会接收到此消息。
总结:dispatchTouchEvent和onTouchEvent函数返回true拦截消息,ACTION_DOWN消息都会被消费掉,即停止传递,正常流程下的后续节点都不会收到消息;
当dispatchTouchEvent返回fasle时,首先拦截消息向子控件中传递,然后将消息传递给父控件的onTouchEvent函数中继续回传。
2、包含onInterceptTouchEvent函数的消息传递流程
只有ViewGroup具有onInterceptTouchEvent函数
在ViewGroup函数中onInterceptTouchEvent函数返回true拦截Action_DOWN消息,消息会流向当前ViewGroup的OnTouchEvent函数,若OnTouchEvent函数没有返回true拦截消息,消息则会继续回传。若在某个OnTouchEvent函数返回true拦截,则消息停止传递。。
ACTION_DOWN消息的传递总结:
1、若dispatchTouchEvent函数和OnTouchEvent函数返回true,消息直接拦截,后续组件不会收到消息
2、若在onInterceptTouchEvent函数拦截消息,只会改变消息的走向,将消息传递给自己的OnTouchEvent函数,不会拦截消息
3、若在dispatchTouchEvent函数返回false拦截消息,会改变消息的正常流向,消息流向父控件的OnTouchEvent函数,并不会截断消息。
4、dispatchTouchEvent函数返回true,消息直接拦截掉
平常开发中使用onInterceptTouchEvent和OnTouchEvent函数就可以实现消息的拦截。
下次记录学习ACTION_MOVE和ACTION_UP消息。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。