Touch Event的分发
点击事件的传递顺序是Activity->Window->View,从上到下依次传递。如果最底层的那个View的onTouchEvent返回false,那就说明这个View不想处理该事件,最终向上传递,让Activity自己来处理。
Touch事件的分发是从dispatchTouchEvent()方法开始的。首先来看下Activity的dispatchTouchEvent()。
1. Activity的dispatchTouchEvent()方法
/**
* Called to process touch screen events. You can override this to
* intercept all touch screen events before they are dispatched to the
* window. Be sure to call this implementation for touch screen events
* that should be handled normally.
*
* @param ev The touch screen event.
*
* @return boolean Return true if this event was consumed.
*/
public boolean dispatchTouchEvent(MotionEvent ev) {
//如果action是ACTION_DOWN,则调用onUserInteraction方法指示有触摸事件发生
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
// 调用PhoneWindow的superDispatchTouchEvent方法,将event分发给Window处理。如果返回false,则说明window或者view没有消费该事件,只能有该Activity来处理该事件。
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
//如果window或view没有消费该event,则由该Activity的onTouchEvent来处理。
return onTouchEvent(ev);
}
/**
* 当一个key事件、触摸事件、滑动球事件发送到该Activity时,会回* 调该方法。
*/
public void onUserInteraction() {
}
从Activity的dispatchTouchEvent可以看到,它会把event传递给Window处理,并根据处理结果来决定是否需要自己来最终处理。如果需要Activity来处理,则调用Activity的onTouchEvent()方法。
/**
* Called when a touch screen event was not handled by any of the views
* under it. This is most useful to process touch events that happen
* outside of your window bounds, where there is no view to receive it.
*
* @param event The touch screen event being processed.
*
* @return Return true if you have consumed the event, false if you haven't.
* The default implementation always returns false.
*/
public boolean onTouchEvent(MotionEvent event) {
if (mWindow.shouldCloseOnTouch(this, event)) {
finish();
return true;
}
return false;
}
2. PhoneWindow的superDispatchTouchEvent()方法
Window中的superDispatchTouchEvent()方法是一个抽象方法,具体由它的子类PhoneWindow来实现。
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
//调用DecorView的superDispatchTouchEvent方法
return mDecor.superDispatchTouchEvent(event);
}
public boolean superDispatchTouchEvent(MotionEvent event) {
//调用到ViewGroup的dispatchTouchEvent事件中
return super.dispatchTouchEvent(event);
}
3.ViewGroup的dispatchTouchEvent()
ViewGroup处理点击事件的大致流程如下:如果ViewGroup接受了一个点击事件,那么首先会调用他的dispatchTouchEvent方法,接着调用ViewGroup的onInterceptTouchEvent方法,如果onInterceptTouchEvent方法返回true,那就代表要拦截这个事件。接下来这个事件就给ViewGroup自己处理了,从而ViewGroup的onTouchEvent方法会被调用。
如果这个ViewGroup的onInterceptTouchEvent反复false,就代表ViewGroup不拦截这个事件,然后把这个事件传递给自己的子元素,然后子元素的dispatchTouchEvent就会被调用,就这样一直循环直到事件被处理。
用伪代码来表示如下:
public boolean dispatchTouchEvent(MotionEvent ev){
boolean consume = false;
//判断ViewGroup是否拦截
if(onInterceptTouchEvent(ev)){
//如果拦截的话,则由它的onTouchEvent来实现
consume = onTouchEvent(ev);
}else{
//如果不拦截,则由它的子View来处理
consume = child.dispatchTouchEvent(ev);
}
return consume;
}
ViewGroup的dispatchTouchEvent的源码如下:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
......
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
//action的掩码
final int actionMasked = action & MotionEvent.ACTION_MASK;
// Handle an initial down.
// 处理初始的状态
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Throw away all previous state when starting a new touch gesture.
// The framework may have dropped the up or cancel event for the previous gesture
// due to an app switch, ANR, or some other state change.
// 清空之前的触摸状态
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// Check for interception.
// 检查拦截
final boolean intercepted;
//如果需要拦截,需要满足两个条件中的一个,一个是ACTION_DOWN,另外一个是mFirstTouchTarget不为空
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
//是否禁止拦截
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
//调用拦截函数,默认实现是返回false。
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
// If intercepted, start normal event dispatch. Also if there is already
// a view that is handling the gesture, do normal event dispatch.
if (intercepted || mFirstTouchTarget != null) {
ev.setTargetAccessibilityFocus(false);
}
// Check for cancelation.
// 检查取消状态
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
// Update list of touch targets for pointer down, if needed.
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;//接收触摸事件的目标
boolean alreadyDispatchedToNewTouchTarget = false;
//触摸事件没有被取消和拦截,寻找一个接收时间的子View
if (!canceled && !intercepted) {
// 处理ACTION_DOWN事件或者是ACTION_POINTER_DOWN事件
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
final int actionIndex = ev.getActionIndex(); // always 0 for down
final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
: TouchTarget.ALL_POINTER_IDS;
//子View的数量
final int childrenCount = mChildrenCount;
//从子View选出一个接收该触控事件,从头到尾遍历
if (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
......
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, childIndex);
......
//选取出了接收触控事件的子View了
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
mLastTouchDownTime = ev.getDownTime();
if (preorderedList != null) {
// childIndex points into presorted list, find original index
for (int j = 0; j < childrenCount; j++) {
if (children[childIndex] == mChildren[j]) {
mLastTouchDownIndex = j;
break;
}
}
} else {
mLastTouchDownIndex = childIndex;
}
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
//找到了接收了event事件的子View,并将子View添加到接收该event事件子view集合的首部。
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
......
}
}
}
//如果没有找到子View来接收处理该event,则使用最近使用的target来处理该event。
if (newTouchTarget == null && mFirstTouchTarget != null) {
// Did not find a child to receive the event.
// Assign the pointer to the least recently added target.
newTouchTarget = mFirstTouchTarget;
while (newTouchTarget.next != null) {
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}
// Dispatch to touch targets.
//分发event给目标target,如果没有找到目标target,则由ViewGroup自己来处理,因为ViewGroup本身也是一个View。
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
// 分发事件给target,包括新找到接收事件的target。
// Dispatch to touch targets, excluding the new touch target if we already
// dispatched to it. Cancel touch targets if necessary.
TouchTarget predecessor = null;
TouchTarget target = mFirstTouchTarget;
while (target != null) {
final TouchTarget next = target.next;
//前面已经处理过了,直接返回,例如ACTION_DOWN前面处理过了,这里就不重复处理。
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
//如果没有处理,则调用dispatchTransformedTouchEvent方法处理。
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
//如果事件已经取消了,则取消处理后续的事件。
if (cancelChild) {
if (predecessor == null) {
mFirstTouchTarget = next;
} else {
predecessor.next = next;
}
target.recycle();
target = next;
continue;
}
}
predecessor = target;
target = next;
}
}
........
}
if (!handled && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
}
return handled;
}
/**
* Transforms a motion event into the coordinate space of a particular child view,
* filters out irrelevant pointer ids, and overrides its action if necessary.
* If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
*/
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
......
// Perform any necessary transformations and dispatch.
//如果child为null,则ViewGroup自己处理,否则交由child来处理
if (child == null) {
handled = super.dispatchTouchEvent(transformedEvent);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
transformedEvent.offsetLocation(offsetX, offsetY);
if (! child.hasIdentityMatrix()) {
transformedEvent.transform(child.getInverseMatrix());
}
handled = child.dispatchTouchEvent(transformedEvent);
}
// Done.
transformedEvent.recycle();
return handled;
}
4. View的DispatchTouchEvent()事件
View的事件分发过程大致是这样的:当View接收到触摸事件时,首先判断是设置了onTouchListener,如果设置了onTouchListener,并且onTouch方法返回true,则直接返回,表示消费该触摸事件。如果onTouchListener为空或者onTouch方法返回false,则交由View的onTouchEvent来处理,处理事件的顺序是DOWM——MOVE——UP。
在ACTION_DOWN主要是设置PREPRESSED状态,并设置CheckForTap点击检测操作以及长按操作CheckForLongPress检测。
在ACTION_MOVE主要是检测触摸事件是否滑出了屏幕范围。
在ACTION_UP中,根据按压时间来处理,如果按压时间小于100ms,则设置按压状态;如果按压时间大于100ms小于500ms,则执行onClick操作;
如果按压时间大于500ms,则执行onLongClick事件。
具体源码如下:
/**
* 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) {
......
boolean result = false;
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(event, 0);
}
if (onFilterTouchEventForSecurity(event)) {
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
//如果onTouchListener不为空,则执行onTouch事件
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
//如果onTouchListener为空或者onTouch方法返回false,则执行onTouchEvent方法
if (!result && onTouchEvent(event)) {
result = true;
}
}
.....
return result;
}
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();
.......
//只要View是可点击或者是长按的话,则onTouchEvent会返回true,表示该事件被View消费了。
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
(viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
switch (action) {
case MotionEvent.ACTION_UP:
//获取PREPRESSED状态
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
......
if (prepressed) {
setPressed(true, x, y);
}
//如果没有长按事件发生并且也没有被忽略,则执行点击事件
if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
//移除长按回调函数
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) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
//执行点击操作
performClick();
}
}
}
//清楚按压状态
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
//移除点击回调函数
removeTapCallback();
}
mIgnoreNextUpEvent = false;
break;
case MotionEvent.ACTION_DOWN:
mHasPerformedLongPress = false;
boolean isInScrollingContainer = isInScrollingContainer();
if (isInScrollingContainer) {
mPrivateFlags |= PFLAG_PREPRESSED;
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
mPendingCheckForTap.x = event.getX();
mPendingCheckForTap.y = event.getY();
//发生点击操作检测,超时事件为100ms
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
// Not inside a scrolling container, so show the feedback right away
setPressed(true, x, y);
checkForLongClick(0, x, y);
}
break;
//取消操作
case MotionEvent.ACTION_CANCEL:
setPressed(false);
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
case MotionEvent.ACTION_MOVE:
drawableHotspotChanged(x, y);
// Be lenient about moving outside of buttons
//检测是否滑出了触控范围,如果滑出了,则移除点击和长按检测
if (!pointInView(x, y, mTouchSlop)) {
// Outside button
removeTapCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
// Remove any future long press/tap checks
removeLongPressCallback();
setPressed(false);
}
}
break;
}
//返回true。
return true;
}
return false;
}
private final class CheckForTap implements Runnable {
public float x;
public float y;
@Override
public void run() {
mPrivateFlags &= ~PFLAG_PREPRESSED;
setPressed(true, x, y);
checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
}
}
private void checkForLongClick(int delayOffset, float x, float y) {
if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
mHasPerformedLongPress = false;
if (mPendingCheckForLongPress == null) {
mPendingCheckForLongPress = new CheckForLongPress();
}
mPendingCheckForLongPress.setAnchor(x, y);
mPendingCheckForLongPress.rememberWindowAttachCount();
postDelayed(mPendingCheckForLongPress,
ViewConfiguration.getLongPressTimeout() - delayOffset);
}
}