View的事件分发机制源码解析(API28)

View的事件分发机制源码解析(API28)


View是安卓里所有UI控件的父类,当一个点击事件(MotionEvent)传递给一个View时,View的内部是如何处理呢?首先这个事件会传递给View的dispatchTouchEvent方法,由dispatchTouchEvent方法的返回值,来告知ViewGroup这个View是否消费该点击事件。废话不多说,下面就来看dispatchTouchEvent的分析。

View的dispatchTouchEvent()源码分析

 /**
     * 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) {
  //result:当前View是否消费点击事件
  boolean result = false;
  //当前点击事件是否安全,安全则进入if代码段
 if (onFilterTouchEventForSecurity(event)) {

            //1,滚动条拖动且当前View是enable的,处理该事件
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //2,当前View设置了OnTouchListener并且onTouch()方法返回true,处理该事件
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
            //3,第1,2步都没有选择处理该事件,就会调用onTouchEvent(),如果onTouchEvent()返回true,则处理该事件
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }
        //省略代码
            return result;
        }

当一个点击事件传递到View时,首先调用View的dispatchTouchEvent方法。
dispatchTouchEvent方法中,如果这个View设置了OnTouchListener且onTouch()返回true,就不调用onTouchEvent(),否则调用onTouchEvent()。
注意OnClickListener的onClick()方法是在onTouchEvent()里面调用。

View的onTouchEvent()源码分析

   /**
     * 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) {
    //获取当前点击事件的位置和这个View的Flag
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();

//如果这个View是CLICKABLE或者LONG_CLICKABLE或者CONTEXT_CLICKABLE的,则称这个View为可点击的(clickable=true)。
        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;

//如果这个View是DISABLED的,直接返回clickable,不做其他响应(后面的代码不会执行)。
        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                setPressed(false);
            }
            //清除FINGER_DOWN标记
            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
            return clickable;
        }

    //如果设置了代理,则交给代理者处理事件
         if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }
//如果View是可点击的或者设置了TOOLTIP,进入if语句内部,并一定消费当前点击事件(return true),否则不消费事件(return false)
        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
                case MotionEvent.ACTION_UP:
                //ACTION_UP事件,手指抬起
//清空PFLAG3_FINGER_DOWN标志位,这个标志位跟多跟手指按下有关,当不止一根手指在这个View按下时,第一次收到ACTION_DOWN事件,后续会收到ACTION_FINGER_DOWN事件,建议有兴趣可以去查一下
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
                        handleTooltipUp();
                    }
                    //如果View是不可点击的,则清除Tap和长按的检测,清空标志位
                    if (!clickable) {
                        removeTapCallback();
                        removeLongPressCallback();
                        mInContextButtonPress = false;
                        mHasPerformedLongPress = false;
                        mIgnoreNextUpEvent = false;
                        break;
                    }
                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
                    //如果设置了PRESSED或者PREPRESSED标记,进入if体
                    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);
                        }
                         //ACTION_UP的重点在这里,如果mHasPerformedLongPress=false,则移除长按的检测,执行单击事件。
                         //注意:当执行了onLongClickListener的onLongClick方法并返回true的时候,mHasPerformedLongPress为true,否则false。
                        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.
                                //PerformClick其实就是一个Runnable,内部调用了我们设置的onCLickListener的OnClick()方法
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                //把PerformClick放到一个Handler里面,如果放置失败,就立即执行PerformClick
                                if (!post(mPerformClick)) {
                                    performClickInternal();
                                }
                            }
                        }

                        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:
                //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:
                //ACTION_MOVE 手指拖动
                    if (clickable) {
                        drawableHotspotChanged(x, y);
                    }

                    // Be lenient about moving outside of buttons
                    //判断拖动的手指是否离开了当前View的范围,是则移除Tap检测和长按检测,清空标志位
                    if (!pointInView(x, y, mTouchSlop)) {
                        // Outside button
                        // Remove any future long press/tap checks
                        removeTapCallback();
                        removeLongPressCallback();
                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                            setPressed(false);
                        }
                        //移除PFLAG3_FINGER_DOWN标志位
                        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    }
                    break;
            }

            return true;
        }

        return false;
    }

总结一下View的onTouchEvent()方法,只要这个View是可点击的(CLICKABLE或者LONG_CLICKABLE或者CONTEXT_CLICKABLE),则消费该点击事件。

ACTION_DOWN事件(手指按下):清空标记,开启长按检测。
ACTION_MOVE事件(手指拖动):检查手指有没有划出View的范围,有则移除长按检测,并清除一些标记位。
ACTION_UP事件(手指抬起):如果还没执行长按事件(长按检测的时间还没到)或者执行了长按事件但是onLongClickListener的onLongClick()方法返回了false,则移除长按检测,并执行onClickListener的onClick()方法。

参考资料
《Android开发艺术探索》
Android View 事件分发机制 源码解析 (上)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值