文章目录
  • 1. 为何要理解事件分发机制
  • WHY

    当一个按钮同时添加了onClick和onTouch事件,它会怎样执行?


    通过一个简单的demo,我们很容易得到答案,先执行onTouch事件,再执行onClick事件。如果将修改onTouch的返回值修改为true,onClick事件可能会被拦截。
    为啥会这样哦.....


    在事件分发的处理方法中,其中最主要的就是这三个方法:dispatchTouchEvent(),onInterceptTouchEvent(),onTouchEvent()
    其中dispatchTouchEvent中包含onInterceptTouchEvent和onTouchEvent方法。

    源码简化后如下。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
                        
    public boolean dispatchTouchEvent(Motion e) {
    boolean result = false;
    if (onInterceptTouchEvent(e)) {
    //如果当前View截获事件,那么事件就会由当前View处理,即调用onTouchEvent()
    result = onTouchEvent(e);
    } else {
    //如果不截获那么交给其子View来分发
    result = child.dispatchTouchEvent(e);
    }
    return result;
    }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
                        
    public boolean dispatchTouchEvent(Motion e) {
    if (onFilterTouchEventForSecurity(e)) {//检测安全性的方法,可忽略
    if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && mOnTouchListener.onTouch(this, event)) {
    return true;
    }
    if (onTouchEvent(e))
    return true;
    }
    }
    return false;
    }

    当一个button同时注册了onClick和onTouch,当onTouch中的返回值为true时,相当于mOnTouchListener.onTouch(this, event)返回true,因此dispatchTouchEvent直接return true。






    2016/05/23

    Fork me on GitHub