TouchEvent分发机制

触摸事件的传递顺序

触摸屏幕首先调用Activity的dispatchTouchEvent(),可以重写这个方法来拦截本该传递给Window的TouchEvent。

   /**
 * 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) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        // 按下事件触发一个可重写的回调方法
        onUserInteraction();
    }
    if (getWindow().superDispatchTouchEvent(ev)) {
        // 如果Window处理了触摸事件
        return true;
    }
    // Window没有处理触摸事件,那就由Activity处理
    return onTouchEvent(ev);
}

Activity的onTouchEvent()默认返回false

/**
 * 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;
}

所以交给Window处理是这句代码

getWindow().superDispatchTouchEvent(ev)

getWindow()方法返回Window类,查找代码发现具体实现是PhoneWindow,PhoneWindow的superDispatchTouchEvent()方法:

    @Override
public boolean superDispatchTouchEvent(MotionEvent event) {
    return mDecor.superDispatchTouchEvent(event);
}

这个mDecor是一个DecorView

    // This is the top-level view of the window, containing the window decor.
    private DecorView mDecor;

DecorView是PhoneWindow的内部类,继承于FrameLayout

private final class DecorView extends FrameLayout implements RootViewSurfaceTaker {}

他的superDispatchTouchEvent()方法

public boolean superDispatchTouchEvent(MotionEvent event) {
    return super.dispatchTouchEvent(event);
}

调用的是父类的方法,也就是ViewGroup中的dispatchTouchEvent()

ViewGroup的dispatchTouchEvent()

以下代码省去了部分次要代码

    @Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    boolean handled = false;
    // onFilterTouchEventForSecurity()方法实现是当窗口部分被遮挡且设置了FILTER_TOUCHES_WHEN_OBSCURED标志时则返回false,即过滤掉这个TouchEvent,不执行if内语句,最后返回false
    if (onFilterTouchEventForSecurity(ev)) {
       ... 
    }
    return handled;
}

然后看if语句内的实现:
- ACTION_DOWN初始化点击状态

final int action = ev.getAction();
 // Action本身包含action信息和pointer信息,actionMasked就是过滤掉pointer信息,只留下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);
     // 这个方法把FLAG_DISALLOW_INTERCEPT清除掉了,所以子控件无法拦截父布局的ACTION_DOWN
     resetTouchState();
}
  • 判断是否拦截:
// Check for interception. 检测拦截
 final boolean intercepted;
 if (actionMasked == MotionEvent.ACTION_DOWN
        // TouchTarget以链表形式存储,mFirstTouchTarget是链表的第一个。mFirstTouchTarget非空的情况是子View处理了事件才会赋值。所以如果ViewGruop拦截了事件,则ACTION_MOVE和ACTION_UP都不会进到这个if语句里,onInterceptTouchEvent方法不会再调用到了。
         || mFirstTouchTarget != null) {
         // 查看是否设置了ViewGroup不能拦截,对于ACTION_DOWWN总是不能拦截的,所以总是可以调用到onInterceptTouchEvent方法
     final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
     if (!disallowIntercept) {
         // 如果可以拦截,那就调用onInterceptTouchEvent()方法,该方法默认返回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;
 }

根据对以上代码的分析,可以得出以下结论:
1. 如果是ACTION_MOVE和ACTION_UP事件,而且没有子View接收事件的话,intercepted直接为true,不触发onInterceptTouchEvent()。即ViewGroup决定自己接收事件后,就不会再调用到onInterceptTouchEvent()。
2. 如果是ACTION_DOWN事件,则必定触发onInterceptTouchEvent()。
3. 如果是ACTION_MOVE和ACTION_UP事件,而且有子View接收事件,则会根据DISALLOW_INTECEPT标志决定是否调用onInterceptTouchEvent()。
- 分发事件

// 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.
// 是否设置了手势分配到多个子View
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
if (!canceled && !intercepted) {
    ...
}
// 分发TouchEvent,没有child处理的话就自己处理
if (mFirstTouchTarget == null) {
    // 没有目标view,所以把自己当做view
    handled = dispatchTransformedTouchEvent(ev, canceled, null,
            TouchTarget.ALL_POINTER_IDS);
} else {
    // 分发到新的目标上,排除掉已经分发的。如果必要的话取消掉目标
    TouchTarget predecessor = null;
    TouchTarget target = mFirstTouchTarget;
    // 循环每个目标分发TouchEvent
    while (target != null) {
        final TouchTarget next = target.next;
        if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
            // 如果已经分发到新target,而且当前target等于新target,handled就是true,移动到下一个目标
            handled = true;
        } else {
            // 如果没有分发到新target,或者当前target不是新target,就根据child是否设置了NEXT_UP_FLAG或者ViewGroup拦截了这个TouchEvent来决定是否发送ACTION_CANCEL
            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;
    }
}

// Update list of touch targets for pointer up or cancel, if needed.
if (canceled
        || actionMasked == MotionEvent.ACTION_UP
        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
    // 如果是取消或者是ACTION_UP,则重置TouchTarget、清除CANEL_NEXT_UP标志、清除FLAG_DISALLOW_INTERCEPT标志   
    resetTouchState();
} else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
    final int actionIndex = ev.getActionIndex();
    final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
    removePointersFromTouchTargets(idBitsToRemove);
}

如果不是取消动作,也没有拦截的话:

    // If the event is targeting accessiiblity focus we give it to the
    // view that has accessibility focus and if it does not handle it
    // we clear the flag and dispatch the event to all children as usual.
    // We are looking up the accessibility focused host to avoid keeping
    // state since these events are very rare.
    View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
            ? findChildWithAccessibilityFocus() : null;
    // 单独对ACTION_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;

        // Clean up earlier touch targets for this pointer id in case they
        // have become out of sync.
        removePointersFromTouchTargets(idBitsToAssign);
        // 遍历子View
        final int childrenCount = mChildrenCount;
        if (newTouchTarget == null && childrenCount != 0) {
            final float x = ev.getX(actionIndex);
            final float y = ev.getY(actionIndex);
            // Find a child that can receive the event.
            // Scan children from front to back.
            final ArrayList<View> preorderedList = buildOrderedChildList();
            final boolean customOrder = preorderedList == null
                    && isChildrenDrawingOrderEnabled();
            final View[] children = mChildren;
            for (int i = childrenCount - 1; i >= 0; i--) {
                final int childIndex = customOrder
                        ? getChildDrawingOrder(childrenCount, i) : i;
                final View child = (preorderedList == null)
                        ? children[childIndex] : preorderedList.get(childIndex);

                // If there is a view that has accessibility focus we want it
                // to get the event first and if not handled we will perform a
                // normal dispatch. We may do a double iteration but this is
                // safer given the timeframe.
                if (childWithAccessibilityFocus != null) {
                    if (childWithAccessibilityFocus != child) {
                        continue;
                    }
                    childWithAccessibilityFocus = null;
                    i = childrenCount - 1;
                }
                // 判断子View能否接收TouchEvent
                if (!canViewReceivePointerEvents(child)
                        || !isTransformedTouchPointInView(x, y, child, null)) {
                    ev.setTargetAccessibilityFocus(false);
                    continue;
                }

                newTouchTarget = getTouchTarget(child);
                if (newTouchTarget != null) {
                    // Child is already receiving touch within its bounds.
                    // Give it the new pointer in addition to the ones it is handling.
                    newTouchTarget.pointerIdBits |= idBitsToAssign;
                    break;
                }

                resetCancelNextUpFlag(child);
                // 调用子view的dispatchTouchEvent(),根据返回结果决定要不要给mFirstTouchTarget赋值。如果子view没有处理,mFirstTouchTarget就为空,就会给ViewGroup处理。
                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();
                    // 给mFirstTouchTarget赋值,赋值完毕退出循环
                    newTouchTarget = addTouchTarget(child, idBitsToAssign);
                    alreadyDispatchedToNewTouchTarget = true;
                    break;
                }

                // The accessibility focus didn't handle the event, so clear
                // the flag and do a normal dispatch to all children.
                ev.setTargetAccessibilityFocus(false);
            }
            if (preorderedList != null) preorderedList.clear();
        }

        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;
        }
    }

ViewGroup的onInterceptTouchEvent():

public boolean onInterceptTouchEvent(MotionEvent ev) {
    if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
            && ev.getAction() == MotionEvent.ACTION_DOWN
            && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
            && isOnScrollbarThumb(ev.getX(), ev.getY())) {
        return true;
    }
    return false;
}

默认实现是拦截鼠标左键按下在ScrollBar滚动条事件。
在一个点击事件序列中,ViewGroup的onInterceptTouchEvent()有几个特点:
1. ACTION_DOWN事件必定会传给onInterceptTouchEvent()
2. ACTION_DOWN事件要不就是让子View去处理,要不就是ViewGroup自身的onTouchEvent()去处理。所以需要在子View或者ViewGroup本身的onTouchEvent()的ACTION_DOWN时返回true才能接收到后续事件,而不是往上一级找人来处理。
3. 而onTouchEvent()返回为true之后,后续事件就不会调用到onInterceptTouchEvent()了,直接走到onTouchEvent()
4. 如果onInterceptTouchEvent()返回为false,则后续事件都会先传递到这里,然后再传递给目标的onTouchEvent()
5. 如果onInterceptTouchEvent()返回为true,则目标view会接收到同样的事件,只不过Action改成了ACTION_CANCEL,然后事件传递到ViewGroup的onTouchEvent(),也不会再调用onInterceptTouchEvent()了。

dispatchTransformedTouchEvent():把TouchEvent转换成特定子View的坐标内,过滤掉不相关的pointer id,必要时复写action。如果子View是空的,那MotionEvent会发送给这个ViewGroup

   /**
 * 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;

    // 首先处理CANCEL事件,如果child为空,则调用View类的dispatchTouchEvent,如果child非空,则调用其dispatchTouchEvent方法,返回处理结果
    // Canceling motions is a special case.  We don't need to perform any transformations
    // or filtering.  The important part is the action, not the contents.
    final int oldAction = event.getAction();
    if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
        event.setAction(MotionEvent.ACTION_CANCEL);
        if (child == null) {
            handled = super.dispatchTouchEvent(event);
        } else {
            handled = child.dispatchTouchEvent(event);
        }
        event.setAction(oldAction);
        return handled;
    }

    // 对pointer进行处理,如果没有pointer则返回false
    // Calculate the number of pointers to deliver.
    final int oldPointerIdBits = event.getPointerIdBits();
    final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;

    // If for some reason we ended up in an inconsistent state where it looks like we
    // might produce a motion event with no pointers in it, then drop the event.
    if (newPointerIdBits == 0) {
        return false;
    }

    // 如果pointer处理前后数目相等,而且我们也不进行任何不可逆的转换,则可以在本次dispatch中一直重用motion event,只要小心注意恢复做出的改变即可。不然我们就要做一个拷贝了
    // If the number of pointers is the same and we don't need to perform any fancy
    // irreversible transformations, then we can reuse the motion event for this
    // dispatch as long as we are careful to revert any changes we make.
    // Otherwise we need to make a copy.
    final MotionEvent transformedEvent;
    if (newPointerIdBits == oldPointerIdBits) {
        //  新的pointer个数与原有的相同
        if (child == null || child.hasIdentityMatrix()) {
            if (child == null) { // 调用自己作为View的dispatchTouchEvent方法
                handled = super.dispatchTouchEvent(event);
            } else { // 根据child的位置和自己的内容滑动距离来算出在child中的坐标,传给child后再恢复初始坐标
                final float offsetX = mScrollX - child.mLeft;
                final float offsetY = mScrollY - child.mTop;
                event.offsetLocation(offsetX, offsetY);

                handled = child.dispatchTouchEvent(event);

                event.offsetLocation(-offsetX, -offsetY);
            }
            // 返回处理结果
            return handled;
        }
        // child非空而且没有identityMatrix,则拷贝这个event
        transformedEvent = MotionEvent.obtain(event);
    } else {
        // 新的pointer个数与原有的不同,那就分割到只剩指定的pointer
        transformedEvent = event.split(newPointerIdBits);
    }

    // 与上面处理基本一样
    // Perform any necessary transformations and dispatch.
    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;
}

View中的dispatchTouchEvent方法:

返回结果是触摸事件是否被OnTouchListener或者onTouchEvent()处理了

    /**
 * 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 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);
    }
    // TouchEvent处理结果
    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
        // 对于ACTION_DOWN,停止NestedScroll
        stopNestedScroll();
    }
    // 跟ViewGroup一样的遮蔽判断
    if (onFilterTouchEventForSecurity(event)) {
        if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
            // 如果当前View是enabled,而且该操作是拖动ScrollBar,设置事件处理成功
            result = true;
        }
        //noinspection SimplifiableIfStatement
        ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnTouchListener != null
                && (mViewFlags & ENABLED_MASK) == ENABLED
                && li.mOnTouchListener.onTouch(this, event)) {
                // 如果当前View是enabled,而且有设置OnTouchListener,则调用OnTouchListener的onTouch方法
            result = true;
        }
        // 如果这个事件没有被作为拖动ScrollBar消耗掉,也没有被OnTouchListener的onTOuch方法消耗掉,那就调用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.
    // 如果是ACTION_UP或ACTION_CANCEL,则在停止内嵌滑动,或者说如果这是ACTION_DOWN,但是上面的三种方式都没有消耗掉这个事件,也停止内嵌滑动
    if (actionMasked == MotionEvent.ACTION_UP ||
            actionMasked == MotionEvent.ACTION_CANCEL ||
            (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
        stopNestedScroll();
    }
    // 返回事件处理结果
    return result;
}

View的onTouchEvent方法:

如果view是可点击的,就返回true,否则返回false。

    /**
 * Implement this method to handle touch screen motion events.
 * <p>
 * If this method is used to detect click actions, it is recommended that
 * the actions be performed by implementing and calling
 * {@link #performClick()}. This will ensure consistent system behavior,
 * including:
 * <ul>
 * <li>obeying click sound preferences
 * <li>dispatching OnClickListener calls
 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
 * accessibility features are enabled
 * </ul>
 *
 * @param event The motion event.
 * @return True if the event was handled, false otherwise.
 */
public boolean onTouchEvent(MotionEvent event) {
    final float x = event.getX();
    final float y = event.getY();
    final int viewFlags = mViewFlags;
    final int action = event.getAction();

    if ((viewFlags & ENABLED_MASK) == DISABLED) {
        // 如果当前View是DISABLED的,直接返回结果
        if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
            // ACTION_UP情况下设为非pressed
            setPressed(false);
        }
        // disabled的View如果是可点击、可长按或者是ContextClickable的话,也会消耗TouchEvent,只是没有任何反应而已
        // A disabled view that is clickable still consumes the touch
        // events, it just doesn't respond to them.
        return (((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
    }
    // 如果设置了修改点击范围的TouchDelegate,则把事件传递过去
    if (mTouchDelegate != null) {
        if (mTouchDelegate.onTouchEvent(event)) {
            return true;
        }
    }
    // 当前View是ENABLED,TouchEvent也没有被代理消耗掉
    if (((viewFlags & CLICKABLE) == CLICKABLE ||
            (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
            (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
        // ENABLED,而且满足CLICKABLE或者LONG_CLICKABLE或者CONTEXT_CLICKABLE。如果都不满足直接返回false未处理
        switch (action) {
            case MotionEvent.ACTION_UP:
                // prepressed状态是ACTION_DOWN后的一段极短时间的状态,过完才算pressed状态
                boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
                if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
                    // 处于prepressed或者pressed状态
                    // take focus if we don't have it already and we should in
                    // touch mode.
                    boolean focusTaken = false;
                    if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                        // 如果当前是focusable而且focusableInTouchMode而且没有focused,就获取focus
                        focusTaken = requestFocus();
                    }

                    if (prepressed) {
                        // 预点击状态下就走到这个ACTION_UP分支,还是显示点击状态效果让用户可见
                        // The button is being released before we actually
                        // showed it as pressed.  Make it show the pressed
                        // state now (before scheduling the click) to ensure
                        // the user sees it.
                        setPressed(true, x, y);
                   }

                    if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                        // 没有长按,只是个tap,移除长按回调
                        // 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) {
                                mPerformClick = new PerformClick();
                            }
                            // 在Runnable中调用performClick或者添加到队列中失败时自行调用performClick方法,performClick中会调用到OnCLickListener
                            if (!post(mPerformClick)) {
                                performClick();
                            }
                        }
                    }

                    if (mUnsetPressedState == null) {
                        mUnsetPressedState = new UnsetPressedState();
                    }

                    if (prepressed) {
                        postDelayed(mUnsetPressedState,
                                ViewConfiguration.getPressedStateDuration());
                    } else if (!post(mUnsetPressedState)) {
                        // If the post failed, unpress right now
                        mUnsetPressedState.run();
                    }

                    removeTapCallback();
                }
                mIgnoreNextUpEvent = false;
                break;

            case MotionEvent.ACTION_DOWN:
                mHasPerformedLongPress = false;

                if (performButtonActionOnTouchDown(event)) {
                    break;
                }

                // Walk up the hierarchy to determine if we're inside a scrolling container.
                boolean isInScrollingContainer = isInScrollingContainer();

                // For views inside a scrolling container, delay the pressed feedback for
                // a short period in case this is a scroll.
                if (isInScrollingContainer) {
                    mPrivateFlags |= PFLAG_PREPRESSED;
                    if (mPendingCheckForTap == null) {
                        mPendingCheckForTap = new CheckForTap();
                    }
                    mPendingCheckForTap.x = event.getX();
                    mPendingCheckForTap.y = event.getY();
                    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;
        }

        return true;
    }

    return false;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值