美文网首页Android自定义View
Android View 事件分发机制

Android View 事件分发机制

作者: hewenyu | 来源:发表于2018-04-24 16:52 被阅读2次

    前言

    貌似简书的代码块没有显示第几行,可以查看csdn上的文章;
    项目开发的过程中经常会使用到自定义控件的功能,而作为自定义控件中的一大重点也是难点就是关于View的事件分发/拦截机制,笔者在刚开始学习自定义控件的时候就经常困惑与此。网上关于这方面的博客非常多,转载的文章也很多,大多数是通过Demo演示来讲解,个人感觉比较经典的几篇有:郭神Carson_Ho。不过再好的文章也只是帮助你理解,想要彻底掌握,唯一的途径还是自己去看源码,本篇博文将从源码的角度来解读事件分发;

    相关方法

    事件分发:
    boolean dispatchTouchEvent(MotionEvent event)
    事件拦截(只存在于ViewGroup中):
    boolean onInterceptTouchEvent(MotionEvent event)
    事件消费(返回true时消费):
    boolean onTouchEvent(MotionEvent event)onTouch(MotionEvent event)
    这几个方法基本上就是事件分发/拦截的关键,很明显,我们能看出这几个方法都有一个 MotionEvent 类型的形参,它表示用户手指触碰到屏幕到抬起,产生的一系列的事件的封装,例如:手指触碰到屏幕的瞬间会有一个MotionEvent.ActionDown事件,手指抬起的瞬间会有一个MotionEvent.ActionUp事件;
    此外,MotionEvent 对象中还封装了几个非常重要的参数:
    getX()/getY(): 表示事件源到当前View左上角的x/y坐标;
    getRawX()/getRawY(): 表示事件源到手机屏幕左上角的x/y坐标;

    View 事件分发

    在开始之前我们先来看一下这几个问题:
    1.点击事件OnClickListener和长按事件OnLongClickListener之间有什么联系;
    2.onTouchEvent和点击事件之间有什么联系;
    3.onTouchEventonTouch两个方法之间有什么联系;

    由于View没有事件拦截方法,因此,当事件传播到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 (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }
    
        if (onFilterTouchEventForSecurity(event)) {
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                return true;
            }
    
            if (onTouchEvent(event)) {
                return true;
            }
        }
    
            if (mInputEventConsistencyVerifier != null) {
                mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
            }
            return false;
        }
    
    
    

    代码不多,我们通过第16行和第21行的两行代码可以看出,如果用户设置了onTouchListener监听,并且返回true(消费了事件),就会直接结束方法,如果没有设置onTouchListener监听或者返回false(不消费事件),才会去调用onTouchEvent方法,看到这里我们就知道了上述的第3个问题的答案:onTouch方法会优先于onTouchEvent方法执行,并且有权决定是否继续执行后续的代码
    接下来我们看第6行官方给出的注释,该方法的返回值表明了此控件是否持有Event,dispatchTouchEvent方法默认返回false,因此实际操作返回值的是onTouchonTouchEvent两个方法,监听事件我们可以忽略,因此我们接下来直接看onTouchEvent方法,同样的,我们先上一段源码:

    /**
     *
     * @param event The motion event.
     * @return True if the event was handled, false otherwise.
     */
    public boolean onTouchEvent(MotionEvent event) {
    
        (....省略代码....)
    
        // 只要代码进入了此条件,就会消费事件
        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) {
                        // 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);
                       }
    
                        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) {
                                    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();
                    }
                    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();
                        }
                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
                    } else {
                        // Not inside a scrolling container, so show the feedback right away
                        setPressed(true);
                        checkForLongClick(0);
                    }
                    break;
    
                case MotionEvent.ACTION_CANCEL:
                    setPressed(false);
                    removeTapCallback();
                    removeLongPressCallback();
                    break;
    
                case MotionEvent.ACTION_MOVE:
                    final int x = (int) event.getX();
                    final int y = (int) event.getY();
    
                    // 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;
    }
    
    

    这个方法的代码量比较大,不过没关系,我们只看关键性的代码:
    既然此方法的返回值表示是否消费事件,那么我们先来看返回值,第116行代码,默认返回false(不消费);
    我们再来第11行的判断语句,只要View是可点击的或者是可以长按点击 的最终都会执行到113行代码消费掉事件,而且只要控件设置了onClickListeneronLongClickListener,必定是可以点击的,如果不设置监听,则需要根据具体的控件来区分(如果不确定,我们可以在我们需要的控件上设置 clickable = true 即可)。
    接下来的关键就是对MotionEvent事件不同状态的分析,我们先来看 ActionDown 事件:

    • 第65行MotionEvent.ActionDown:
      可以看到66行将 mHasPerformedLongPress 设置为false,此变量最终会影响到 onClick 方法是否执行,然后在77行判断是否是可以滚动的容器(ScrollView等),如果不是最后会执行86行的检查长按监听,再此方法中会创建一个实现了Runnable接口的CheckForLongPress对象,然后发送一个延迟消息(500ms),如果设置了长按监听,时间到了还没有移除长按监听的callback,就会执行run方法里面的 performLongClick 方法,其返回值就是我们的 onLongClick 的返回值,默认为 false;
    private void checkForLongClick(int delayOffset) {
        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
            mHasPerformedLongPress = false;
    
            if (mPendingCheckForLongPress == null) {
                mPendingCheckForLongPress = new CheckForLongPress();
            }
            mPendingCheckForLongPress.rememberWindowAttachCount();
            postDelayed(mPendingCheckForLongPress,
                    ViewConfiguration.getLongPressTimeout() - delayOffset);
        }
    }
    
    class CheckForLongPress implements Runnable {
    
        private int mOriginalWindowAttachCount;
    
        public void run() {
            if (isPressed() && (mParent != null)
                    && mOriginalWindowAttachCount == mWindowAttachCount) {
                if (performLongClick()) {
                    mHasPerformedLongPress = true;
                }
            }
        }
    
        public void rememberWindowAttachCount() {
            mOriginalWindowAttachCount = mWindowAttachCount;
        }
    }
    
    
    • 第14行 MotionEvent.ActionUp:
      我们直接看到 onTouchEvent 方法中的第32行代码,前面我们说过 mHasPerformedLongPress 默认为false,只有设置了长按监听并且返回为 true 的时候才会为true;到这里我们就可以知道我们的第1个问题的答案了:如果设置了onLongClickListener,会优先于onClickListener监听执行,同时,其返回值能够决定点击事件是否能够执行;
      我们再看到第45行代码,performClick() 方法回去判断我们是否设置了onClickListener,如果设置了会去执行它的onClick方法;
    public boolean performClick() {
        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
    
        ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnClickListener != null) {
            playSoundEffect(SoundEffectConstants.CLICK);
            li.mOnClickListener.onClick(this);
            return true;
        }
    
        return false;
    }
    

    到这里,我们可以得到我们第2个问题的结论:onTouchEvent()方法在执行ActionUp事件的时候,会根据onLongClick()的返回值,决定是否执行onClick();

    总结

    关于View的事件分发到这里就结束了,总的来说不是很难,跟着源码的逻辑走一遍基本上就能理解的差不多,关键是几个方法的之间的逻辑关系需要弄明白,写文章能够帮自己抽时间理清楚的思路记录下来,方便以后用到的时候查阅;
    本文有很多方法没有展开讲解,如果源码放的太多会使文章看的很枯燥,然后如果想详细了解的主要还是要自己跟着源码走一遍,源码类型的文章主要还是为了帮助自己记录阅读源码时候的一些关键点;

    相关文章

      网友评论

        本文标题:Android View 事件分发机制

        本文链接:https://www.haomeiwen.com/subject/dfxhqftx.html