关于安卓View的事件分发,ontouch和ontouchevent 这两个方法的疑问...

发布网友

我来回答

1个回答

热心网友

touch事件在View树中的传递是从根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) {
    ...
    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;
        }
    }
    ...
    return false;
}

可以看到onTouchListener.onTouch方法的优先级是比OnTouchEvent高的,如果控件已经设置了OnTouchListener并且其中的ontouch方法返回true,那么touch事件就被自己定义的拦截,ontouchevent方法不会执行,否则还会继续执行控件内定义的onTouchEvent方法

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com