c. View对touch事件的处理
View的dispatchTouchEvent方法的主要代码如下:
public boolean dispatchTouchEvent(MotionEvent event) {
boolean result = false;
. . .
if (onFilterTouchEventForSecurity(event)) {
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
if (!result && onTouchEvent(event)) {
result = true;
}
. . .
return result;
}
由上述代码可知,View对touch事件的处理过程如下:由于View不包含子元素,所以它只能自己处理事件。它首先会判断是否设置了OnTouchListener,若设置了,会调用onTouch方法,若onTouch方法返回true(表示该touch事件已经被消耗),则不会再调用onTouchEvent方法;若onTouch方法返回false或没有设置OnTouchListener,则会调用onTouchEvent方法,onTouchEvent对touch事件进行具体处理的相关代码如下:
if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
. . .
if (!mHasPerformedLongPress) {
//This is a tap, so remove the longpress check
removeLongPressCallback();
//Only perform take click actions if we were in the pressed state
if (!focusTaken) {
//Use a Runnable and post this rather than calling performClick directly.
//This lets other visual state of the view update before click actions start.
if (mPerformClick == null) {
mPerformClck = new PeformClick();
}
if (!post(mPerformClick)) {
performClick();
}
}
}
. . .
}
break;
}
. . .
return true;
}










