安卓事件分发机制

以下:部分内容截取自《Android开发艺术探索》,内容仅用于自我记录学习使用。

  1. 对ViewGroup, 事件分发的相关方法有三个:dispatchTouchEvent,onInterceptTouchEvent,onTouchEvent。dispatchTouchEvent,对ViewGroup并无太大意义,决定是否分发给子元素的关键点在于onInterceptTouchEvent() 的返回值,返回为true则ViewGroup自我消化该事件,false则分发给子View。当返回true的时候会调用ViewGroup 的onTouchEvent事件。
  2. 当ViewGroup分发事件给子元素时,子元素会调用dispatchTouchEvent,onInterceptTouchEvent(如果子元素还是ViewGroup), onTouchEvent(如果事件是当前元素处理)。依次反复,实现事件分发。
  3. 对View,事件分发的相关方法有两个:dispatchTouchEvent、onTouchEvent。
  4. 对View,onTouchListener/onClickListener的优先级要高于onTouchEvent/onClickEvent。即当这个View设置了onTouchListener或者onClickListener事件时,则相应的View中的onTouchEvent或者onClickEvent则不会被调用。但是当onTouchListener/onClickListener返回值为false时则表示该事件未被消费,则会继续调用View的onTouchEvent/onClickEvent。
  5. 事件传递顺序:Activity -> Window ->View。即事件总是先传递给Activity,再传递给Window,再传递给顶层View。顶层View接收到事件后会按照事件分发机制去分发事件。如果一个View的onTouchEvent返回false,则其父元素的onTouchEvent会被调用,以此类推,如果所有的元素都不处理这个事件,则会交给Activity处理,即调用Activity的onTouchEvent事件。
  6. 正常情况下一个事件只能被一个元素拦击。因为一旦一个元素拦截了该事件,则同一个事件序列内(move, up等)的所有事件都会交于该View处理。并且一旦该元素决定拦截该事件时,(如果是ViewGroup)其onInterceptTouchEvent不会再被调用。
  7. 一次完成的触摸事件应当包括Action_Down、Action_Move、Aciton_UP,其中Action_Move的数量可为若干个,也可为0个,Down和Up事件只能有一个。
  8. 事件触发的顺序是onTouchEvent -> onLongClickEvent -> onClickEvent
  9. ViewGroup默认不拦截任何事件,onInterceptTouchEvent默认返回false。View没有onInterceptTouchEvent方法,一旦有事件传递给View,就用调用onTouchEvent,并且View默认消耗事件,onTouchEvent默认返回true,除非他的clickable和longClickable都为false,
  10. 若一个View一旦开始处理事件,如果其不消耗DOWN事件(返回false),则统一事件序列中的其他事件都不会再交给他来处理,并将事件交于他的父元素处理,父元素的onTouchEvent会被调用。
  11. 事件的传递是由外向内,在子元素中可以通过this.getParent().requestDisallowInterceptTouchEvent(true); 干预父元素的事件拦截,将事件分发给子元素,但是无法干预父元素的Down事件接收(不会拦截,因为代码中将标识为复位了,所以DOWN事件无法干预。。。貌似这样的吧。。。。。)。

注:以下代码翻译借助有道词典。。。。。还有一些私人的小想法。。。。对于具体的事件分发讲解可以参考这篇博客:https://www.cnblogs.com/linjzong/p/4191891.html

ViewGroup源码

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // 输入事件一致性校验
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }

        // If the event targets the accessibility focused view and this is it, start
        // normal event dispatch. Maybe a descendant is what will handle the click.
        // 如果事件的目标是可访问性焦点视图,那么启动正常的事件分派。也许后代就是处理点击的对象。
        if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
            ev.setTargetAccessibilityFocus(false);
        }

        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) {    // 过滤触摸事件以应用安全策略。 估计是过滤事件,确定是安全的点击事件
            final int action = ev.getAction();
            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.
                // 当开始一个新的触摸手势时,扔掉所有以前的状态。
                // 由于应用程序切换、ANR或其他状态变化,框架可能已经删除了上一个手势的up或cancel事件。
                // 即ViewGroup发现事件是DOWN事件时就会将状态还原,包括FLAG_DISALLOW_INTERCEPT标识,
                // 这就导致设置设置FLAG_DISALLOW_INTERCEPT标识无法拦截Down事件,因为Down事件会把标志位重置
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }

            // Check for interception.
            // 检查拦截。
            final boolean intercepted;
            // 如果是DOWN事件 或 mFirstTouchTarget != null (mFirstTouchTarget:当事件分发给子View处理时mFirstTouchTarget会被指向子View,不为空则表示该事件被子View处理)
            // 即当ViewGroup拦截事件时, mFirstTouchTarget != null不成立,且MOVE和UP事件会直接进入else,不会再触发onInterceptTouchEvent() 方法。同时设置intercepted = true表示事件被自身拦截
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                // DOWN事件来临时,如果设置了requestDisallowInterceptTouchEvent。则会走哪我也不清楚
                // 当走if时,ViewGroup 的onInterceptTouchEvent方法默认返回false,else中也是设置成false,差不多差不多。
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    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.
            // 如果被拦截,启动正常的事件调度。另外,如果已经有一个视图在处理这个手势,请执行正常的事件调度。
            // intercepted = true表示被ViewGroup自身拦截,或者被子View拦截设置设置事件不可访问焦点
            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;
            // 当intercepted = false时则代表要分发给子View,且没有ACTION_CANCEL 取消事件。则给子View分发事件
            if (!canceled && !intercepted) {

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

                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.
                    // 清理这个指针id的早期触摸目标,以防它们变得不同步。
                    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 = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        // 循环子View
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = getAndVerifyPreorderedIndex(
                                    childrenCount, i, customOrder);
                            final View child = getAndVerifyPreorderedView(
                                    preorderedList, children, 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;
                            }

                            // canViewReceivePointerEvents 如果子视图可以接收指针事件,则返回true。
                            // isTransformedTouchPointInView 如果子视图在转换为其坐标空间时包含指定的点,则返回true。
                            // 如果子View在播放动画或者点击事件坐标不在子元素区域内则放弃这次循环
                            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);
                            // 如果不取消事件,且child不为null则调用子View的dispatchTouchEvent方法,从而将事件交给子元素进行处理,结束了一轮事件分发
                            // 如果子元素dispatchTouchEvent返回为true,则进入if循环。如果返回false则会将事件分发给下一个子元素
                            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,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;
                    }
                }
            }

            // Dispatch to touch targets.
            // 进入if则交给ViewGroup自身处理,分发给子View失败,进入else则说明成功
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                // 这里传参child为null,则会调用super.dispatchTouchEvent(event);并返回,即将此次事件转到了View的dispatchTouchEvent方法,即点击事件开始交给ViewGroup的父类View处理。
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
                // 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;
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        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) {
                resetTouchState();
            } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
                final int actionIndex = ev.getActionIndex();
                final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
                removePointersFromTouchTargets(idBitsToRemove);
            }
        }

        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;

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

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

        // 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) {
            if (child == null || child.hasIdentityMatrix()) {
                if (child == null) {
                    handled = super.dispatchTouchEvent(event);
                } else {
                    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;
            }
            transformedEvent = MotionEvent.obtain(event);
        } else {
            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;
    }


    /**
     * Adds a touch target for specified child to the beginning of the list.
     * Assumes the target child is not already present.
     */
    private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
        final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
        target.next = mFirstTouchTarget;
        mFirstTouchTarget = target;
        return target;
    }

View源码

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

        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();     // 停止正在进行的嵌套滚动
        }
//        过滤触摸事件以应用安全策略。  --- 如果事件应该被分派,则为True;如果事件应该被删除,则为false。
        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //noinspection SimplifiableIfStatement
            // 检查是否设置了OnTouchLinstener,因为触摸监听事件优先级高于OnTouchEvent事件
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {      // 调用onTouch并根据其返回结果设置该事件是否被消耗
                result = true;
            }
            // 如果没有设置检查是否设置了OnTouchLinstener则调用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_DOWN但不想要这个手势的其余部分,也要取消它。
        if (actionMasked == MotionEvent.ACTION_UP ||
                actionMasked == MotionEvent.ACTION_CANCEL ||
                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
            stopNestedScroll();
        }

        return result;
    }
    /**
     * 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();

        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
        //     若一个View是disable的,如果它是 CLICKABLE或者LONG_CLICKABLE或CONTEXT_CLICKABLE的就返回true,表示消耗掉了Touch事件
        // 即即使View在不可用状态下,依旧会消耗事件
        // 只要 CLICKABLE 或者 LONG_CLICKABLE有一个为true,都会消耗该事件,即onTouchEvent会返回true。不管其是不是DISABLE状态
        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                setPressed(false);
            }
            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
            return clickable;
        }
        // 如果View设置代理,则执行下面
        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }

        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
                // 当事件为UP事件时,会触发performClick() 方法,如果View设置了OnClickListenter,则performClick()会调用onClick方法
                case MotionEvent.ACTION_UP:
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
                        handleTooltipUp();
                    }
                    if (!clickable) {
                        removeTapCallback();
                        removeLongPressCallback();
                        mInContextButtonPress = false;
                        mHasPerformedLongPress = false;
                        mIgnoreNextUpEvent = false;
                        break;
                    }
                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
                        // take focus if we don't have it already and we should in
                        // touch mode.
                        // 触摸模式下如果还没获取焦点则获取焦点
                        boolean focusTaken = false;
                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                            focusTaken = requestFocus();
                        }

                        if (prepressed) {
                            // 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) {
                            // 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.
                                // 使用一个Runnable并发布它,而不是直接调用performClick。这允许在单击动作开始之前更新视图的其他视觉状态。

                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();     // 里面创建了一个子线程
                                }
                                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:
                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
                    }
                    mHasPerformedLongPress = false;

                    if (!clickable) {
                        checkForLongClick(0, x, y);
                        break;
                    }

                    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:
                    if (clickable) {
                        setPressed(false);
                    }
                    removeTapCallback();
                    removeLongPressCallback();
                    mInContextButtonPress = false;
                    mHasPerformedLongPress = false;
                    mIgnoreNextUpEvent = false;
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    break;

                case MotionEvent.ACTION_MOVE:
                    if (clickable) {
                        drawableHotspotChanged(x, y);
                    }

                    // Be lenient about moving outside of buttons
                    if (!pointInView(x, y, mTouchSlop)) {
                        // Outside button
                        // Remove any future long press/tap checks
                        removeTapCallback();
                        removeLongPressCallback();
                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                            setPressed(false);
                        }
                        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    }
                    break;
            }

            return true;
        }

        return false;
    }

    /**
     * Register a callback to be invoked when this view is clicked. If this view is not
     * clickable, it becomes clickable.
     *
     * @param l The callback that will run
     *
     * @see #setClickable(boolean)
     */
    public void setOnClickListener(@Nullable OnClickListener l) {
        if (!isClickable()) {
            setClickable(true);
        }
        getListenerInfo().mOnClickListener = l;
    }

    /**
     * Return whether this view has an attached OnClickListener.  Returns
     * true if there is a listener, false if there is none.
     */
    public boolean hasOnClickListeners() {
        ListenerInfo li = mListenerInfo;
        return (li != null && li.mOnClickListener != null);
    }

    /**
     * Register a callback to be invoked when this view is clicked and held. If this view is not
     * long clickable, it becomes long clickable.
     *
     * @param l The callback that will run
     *
     * @see #setLongClickable(boolean)
     */
    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
        if (!isLongClickable()) {
            setLongClickable(true);
        }
        getListenerInfo().mOnLongClickListener = l;
    }

CLICKABLE 具体值跟不同View有关,LONG_CLICKABLE属性默认false。
setOnClickListener会将CLICKABLE 设置为true, setOnLongClickListener会将LONG_CLICKABLE设置为true。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猫吻鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值