View中的onTouchEvent()与setOnTouchListener()中的ontouch()方法的事件处理先后顺序

时间:2023-11-24 17:57:44

Touch事件的两种情况
1.覆写View.class中定义的onTouchEvent-->基于事件回调监听方式

@Override
public boolean onTouchEvent(MotionEvent ev) {
// TODO
return super.onTouchEvent(ev);
}

2.通过监听的形式,监听View.class中的setOnTouchListener(listener)--->基于监听器事件监听方式

/**
* Register a callback to be invoked when a touch event is sent to this view.
* @param l the touch listener to attach to this view
*/
public void setOnTouchListener(OnTouchListener l) {
getListenerInfo().mOnTouchListener = l;
} public interface OnTouchListener {
/**
* Called when a touch event is dispatched to a view. This allows listeners to
* get a chance to respond before the target view.
*
* @param v The view the touch event has been dispatched to.
* @param event The MotionEvent object containing full information about
* the event.
* @return True if the listener has consumed the event, false otherwise.
*/
boolean onTouch(View v, MotionEvent event);
}

3.两个方法的调用顺序是怎样
经过debug测试,基于监听器的优先于基于回调的,源码上分析也一样.
4.基于监听器的返回值值是否影响基于回调的

父类方法中会先判断接口回调的是不是返回true,是的话就不执行ontouch方法
会影响,如果return true,基于回调onTouch就不执行

5.举个栗子:
在一个Activity里面放一个TextView的实例tv,并且这个tv的属性设定为 fill_parent
在这种情况下,当手放到屏幕上的时候,首先会是tv响应touch事件,执行onTouch方法。

如果onTouch返回值为true,
表示这个touch事件被onTouch方法处理完毕,不会把touch事件再传递给Activity,
也就是说onTouchEvent方法不会被调用。
(当把手放到屏幕上后,onTouch方法被一遍一遍地被调用)

如果onTouch的返回值是false,
表示这个touch事件没有被tv完全处理,onTouch返回以后,touch事件被传递给Activity,
onTouchEvent方法被调用。