关于安卓View的事件分发,ontouch和ontouchevent 这两个方法的疑问....
发布网友
发布时间:2022-04-28 12:49
我来回答
共1个回答
热心网友
时间:2023-10-09 11:43
touch事件在View树中的传递是从根View的dispatchTouchEvent方法开始的,贴一下View类dispatchTouchEvent方法源码
/**
* Pass the touch screen motion event down to the target view, or this
* view if it is the target.
*
* @param event The motion event to be dispatched.
* @return True if the event was handled by the view, false otherwise.
*/
public boolean dispatchTouchEvent(MotionEvent event) {
...
if (onFilterTouchEventForSecurity(event)) {
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && li.mOnTouchListener.onTouch(this, event)) {
return true;
}
if (onTouchEvent(event)) {
return true;
}
}
...
return false;
}
可以看到onTouchListener.onTouch方法的优先级是比OnTouchEvent高的,如果控件已经设置了OnTouchListener并且其中的ontouch方法返回true,那么touch事件就被自己定义的*拦截,ontouchevent方法不会执行,否则还会继续执行控件内定义的onTouchEvent方法
热心网友
时间:2023-10-09 11:43
touch事件在View树中的传递是从根View的dispatchTouchEvent方法开始的,贴一下View类dispatchTouchEvent方法源码
/**
* Pass the touch screen motion event down to the target view, or this
* view if it is the target.
*
* @param event The motion event to be dispatched.
* @return True if the event was handled by the view, false otherwise.
*/
public boolean dispatchTouchEvent(MotionEvent event) {
...
if (onFilterTouchEventForSecurity(event)) {
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && li.mOnTouchListener.onTouch(this, event)) {
return true;
}
if (onTouchEvent(event)) {
return true;
}
}
...
return false;
}
可以看到onTouchListener.onTouch方法的优先级是比OnTouchEvent高的,如果控件已经设置了OnTouchListener并且其中的ontouch方法返回true,那么touch事件就被自己定义的*拦截,ontouchevent方法不会执行,否则还会继续执行控件内定义的onTouchEvent方法