Android事件分发04——View的dispatchTouchEvent
前面我们开了好久的车,从 Activity的dispatchTouchEvent开始,途径ViewGrop的dispatchTouchEvent,现在快到终点站了,那就是view的了,我们一起来看看呗。
首先说明一把: 事件传递到View的dispatchTouchEvent中,主要干以下几步骤:
- 如果控件可用的,并且添加了触摸的监听,那么先执行监听的onTouch
- 第1不没有返回true,开始调用 onTouchEvent
View的dispatchTouchEvent
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)) {
//ListenerInfo 监听的一个聚集类,它里面聚集了我们添加的监听的实例
ListenerInfo li = mListenerInfo;
//触摸监听不为空,并且控件可用,监听的触摸方法,返回true
//那么不用往下执行了
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
//如果上面没有执行,那么我们调用 onTouchEvent方法
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;
}
重点看:25–38行
25—33:触摸监听不为空,控件可用,调用触摸监听的onTouch方法,这个方法返回了true,都满足了,那么我们直接放回true,代表消费了事件。
35–38:如果上面没有瞒住,那么执行onTouchEvent事件来处理事件。
上面的步骤说完,我们来想想一个小问题,有一个控件,我不想响应它的点击等事件,又不重写控件,那么怎么处理呢?
看了上面的代码,我们有个处理方式,给这个控件添加OnTouchListener监听,在它的onTouch方法中返回true。