Android View事件分发(第一节)

作者: PittFS | 来源:发表于2016-09-05 08:36 被阅读249次

    前言

    可能你在工作中遇到过竖直滑动的View中嵌套横向滑动的View(如RecyclerView中嵌套ListView),或者遇到过根据滑动速度或者距离去完成一些事件(如滑动关闭Activity),这都离不开开发者对手指的触摸事件进行处理。

    Android事件传递流程

    当手指按下后,事件传递的过程为:Activity--->Window--->DecorView--->TooBar等或者contentView(DecorView,TooBar,contentView都为View),如图:

    Android事件传递 (14).png

    源码分析

    接下来我将通过源码,分析触控事件的传递过程:

    事件产生后先传递到Activity,接下来我们先看下Activity的源码:

    public boolean dispatchTouchEvent(MotionEvent ev) {
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                onUserInteraction();
            }
            if (getWindow().superDispatchTouchEvent(ev)) {
                return true;
            }
            return onTouchEvent(ev);
        }
    

    在这里我们可以看到,在dispatchTouchEvent方法中,将事件传递给了Window,由于Window是个抽象类,接下来我们将继续追踪PhoneWindow(由于PhoneWindow是Window的唯一实现类,所以追踪PhoneWindow中的代码)中的代码:

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

    这里的代码逻辑很简单,我们可以看到事件传递给了DecorView,接着,我们看下DecorView中的代码:

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

    大家看好,在superDispatchTouchEvent方法中,调用了父类dispatchTouchEvent方法,
    DecorView的父类是FrameLayout,但是我们在FrameLayout并没有发现发现方法的重写,于是我们继续追踪代码到FrameLayout的父类ViewGroup,关于在View以及其子类中的处理,会在下一节中进行详细的分析......

    相关文章

      网友评论

        本文标题:Android View事件分发(第一节)

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