View的dispatchTouchEvent派发比较简单,不需要经过打断这一环。
而是直接去调用onTouchEvent方法,注意View如果存在TouchListener,则TouchListener优先。
看源码:
public boolean dispatchTouchEvent(MotionEvent event) {
// If the event should be handled by accessibility focus first.
if (event.isTargetAccessibilityFocus()) {
// We don't have focus or no virtual descendant has it, do not handle the event.
if (!isAccessibilityFocusedViewOrHost()) {
return false;
}
// We have focus and got the event, then use normal event dispatch.
event.setTargetAccessibilityFocus(false);
}
boolean result = false;
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(event, 0);
}
final int actionMasked = event.getActionMasked();
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Defensive cleanup for new gesture
stopNestedScroll();
}
if (onFilterTouchEventForSecurity(event)) {
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
//如果存在onTouchListener则优先处理,否则去执行onTouchEvent
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
if (!result && onTouchEvent(event)) {
result = true;
}
}
if (!result && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
// Clean up after nested scrolls if this is the end of a gesture;
// also cancel it if we tried an ACTION_DOWN but we didn't want the rest
// of the gesture.
if (actionMasked == MotionEvent.ACTION_UP ||
actionMasked == MotionEvent.ACTION_CANCEL ||
(actionMasked == MotionEvent.ACTION_DOWN && !result)) {
stopNestedScroll();
}
return result;
}
再看看onTouchEvent,如果View是CLICKABLE,LONG_CLICKABLE可点击,返回的是true,处理掉
否则 返回false,不处理。
解释一下为什么ListView中的onInterceptTouchEvent只执行了一次。
ListView重写了onInterceptTouchEvent和onTouchEvent,事件分发使用基类ViewGroup的分发,Item的View是ListView的子View,在Item中放一个TextView,发现只在Down的时候onInterceptTouchEvent执行了一次,为什么呢?因为TextView没有CLICKABLE,Down时是不拦截的,而TextView并没有消化事件,所以Down事件被ListView重写的onTouchEvent本身处理了,所以拦截函数就不会执行啦。
如果有给TextView加上onClickListener,则onTouchEvent处理了Down事件,后续的move还是要判断拦截的,到滑动程度就会拦截。
总结:由dispatchTouchEvent派发给TouchListener或onTouchevent