View事件分发机制全解析

dispatchTouchEvent方法是用来传递Touch(触摸)事件的,它的返回值就是内部声明的result。如果result为true,则会进行分发,也就是view会继续响应触摸事件,但不会向父视图传递。如果为false,则不会分发,无论你如何触摸你的view,都不会处理你触摸事件的逻辑,但事件会传递给父视图进行处理。
从以上可以得到一个概念:分发表示继续处理触摸事件,不分发表示不继续处理触摸事件。
我们先看看这个方法:

public boolean dispatchTouchEvent(MotionEvent event) {
    // If the event should be handled by accessibility focus first.
    if (event.isTargetAccessibilityFocus()) {
        // We don't have focus or no virtual descendant has it, do not handle the event.
        if (!isAccessibilityFocusedViewOrHost()) {
            return false;
        }
        // We have focus and got the event, then use normal event dispatch.
        event.setTargetAccessibilityFocus(false);
    }

    boolean result = false;

    if (mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onTouchEvent(event, 0);
    }

    final int actionMasked = event.getActionMasked();
    if (actionMasked == MotionEvent.ACTION_DOWN) {
        // Defensive cleanup for new gesture
        stopNestedScroll();
    }

    if (onFilterTouchEventForSecurity(event)) {
        //noinspection SimplifiableIfStatement
        ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnTouchListener != null
                && (mViewFlags & ENABLED_MASK) == ENABLED
                && li.mOnTouchListener.onTouch(this, event)) {
            result = true;
        }

        if (!result && onTouchEvent(event)) {
            result = true;
        }
    }

    if (!result && mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
    }

    // Clean up after nested scrolls if this is the end of a gesture;
    // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
    // of the gesture.
    if (actionMasked == MotionEvent.ACTION_UP ||
            actionMasked == MotionEvent.ACTION_CANCEL ||
            (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
        stopNestedScroll();
    }

    return result;
}

第3-22行是对组件的属性或者是点击操作进行处理,一般情况下并不会影响返回的结果。只有第8行返回了false,也就是不分发。但是从它的判断语句if (!isAccessibilityFocusedViewOrHost())的名字可以大概知道,它是用来处理view的无障碍属性的,一般情况下该值都是true,也就是不会执行第8行,而是继续处理下面的逻辑。

要注意到第12行声明了布尔变量result,它就是这个函数的返回值。默认值为false,不进行分发。

接下来我们看看24-36行:
第24行有个if (onFilterTouchEventForSecurity(event))的判断,这个判断是此函数最需要注意的地方(在if语句内部,可以清楚地看到返回的result值在满足一定的条件下,被设置为ture了),我们进入这个判断内部,看看它是怎么处理的,以及onFilterTouchEventForSecurity返回值的布尔值是怎么设置的

/**
 * Filter the touch event to apply security policies.
 *
 * @param event The motion event to be filtered.
 * @return True if the event should be dispatched, false if the event should be dropped.
 *
 * @see #getFilterTouchesWhenObscured
 */
public boolean onFilterTouchEventForSecurity(MotionEvent event) {
    //noinspection RedundantIfStatement
    if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
            && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
        // Window is obscured, drop this touch.
        return false;
    }
    return true;
}

onFilterTouchEventForSecurity只有一个判断,返回值的布尔值只和判断的结果有关系。如果if满足了,就返回false,否则返回true。我们看看这个if判断,它进行了两个位运算。
第一个位运算:mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED。mViewFlags是该View所包含的标志合成信息(包括是否可点击Clikable、可使用的Enable等等,这些标识,可以在Java代码或者xml文件中进行设置,一般可点击的view,这两个属性都为true),所以只需要找到对应的View标志和mViewFlags进行&运算,就能判断当前View是否支持这个标志。因此,我们值需要查看FILTER_TOUCHES_WHEN_OBSCURED,让我们看看它声明的地方:

/**
 * Indicates that the view should filter touches when its window is obscured.
 * Refer to the class comments for more information about this security feature.
 * {@hide}
 */

也就是说,这个标志是来表明当窗口被遮挡的时候,当前view是否需要过滤掉touch事件。过滤的意思就是不进行传递,即是不对后续的触摸事件进行处理。为什么不会对其进行处理呢?如果该标志为真,那么与mViewFlags相&的结果就不等于0,也就满足于onFilterTouchEventForSecurity方法的if判断,最后该方法返回false,导致dispatchTouchEvent不进入if (onFilterTouchEventForSecurity(event))语句内,最终导致dispatchTouchEvent返回result的默认值false(第36行以后不会再修改result的值了)

那么,为什么要过滤掉touch事件呢?我们能从第二个&运算中得到问题的答案:event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED
首先是得到event事件的标志(如按下、抬起、滑动等等),然后与MotionEvent.FLAG_WINDOW_IS_OBSCURED进行&运算。
查看MotionEvent.FLAG_WINDOW_IS_OBSCURED的声明:

/**
 * This flag indicates that the window that received this motion event is partly
 * or wholly obscured by another visible window above it.  This flag is set to true
 * even if the event did not directly pass through the obscured area.
 * A security sensitive application can check this flag to identify situations in which
 * a malicious application may have covered up part of its content for the purpose
 * of misleading the user or hijacking touches.  An appropriate response might be
 * to drop the suspect touches or to take additional precautions to confirm the user's
 * actual intent.
 */
public static final int FLAG_WINDOW_IS_OBSCURED = 0x1;

简而言之,FLAG_WINDOW_IS_OBSCURED是用来检查组件的安全性的。比如说你的view被其他界面部分遮盖或者完全遮盖(假设有个恶意程序故意做成和你view相同的界面,从而劫持了你的触摸事件,诱导你进入到它程序的界面)。所以,拿到这个标志,就能采取一定的预防措施,确定用户的真实意图,如Toast提示用户界面被拦截。

第24行的作用就显而易见了。如果需要过滤当view被遮盖的touch事件,或者view已经半遮盖或者全遮盖住了,则onFilterTouchEventForSecurity返回false,那么dispatchTouchEvent的result为false,也就是不分发事件。如果onFilterTouchEventForSecurity返回true,则分发事件。从该方法的注释@return True if the event should be dispatched, false if the event should be dropped.也可以看出这个结果。

默认情况下,该方法返回的是true,也就进入了25-35行的方法内部:

    //noinspection SimplifiableIfStatement
    ListenerInfo li = mListenerInfo;
    if (li != null && li.mOnTouchListener != null
            && (mViewFlags & ENABLED_MASK) == ENABLED
            && li.mOnTouchListener.onTouch(this, event)) {
        result = true;
    }

    if (!result && onTouchEvent(event)) {
        result = true;
    }

首先是将类型为ListenerInfo的变量li指向mListenerInfo,mListenerInfo是在哪里声明的呢?进行搜索后,可以找到相应的方法:

ListenerInfo getListenerInfo() {
    if (mListenerInfo != null) {
        return mListenerInfo;
    }
    mListenerInfo = new ListenerInfo();
    return mListenerInfo;
}

getListenerInfo是获取mListenerInfo,正是我们要搜索的变量。如果mListenerInfo为空的话,它会new一个新的ListenerInfo()变量。我们看看ListenerInfo类到底是什么:

static class ListenerInfo {
/**
* Listener used to dispatch focus change events.
* This field should be made private, so it is hidden from the SDK.
* {@hide}
*/
protected OnFocusChangeListener mOnFocusChangeListener;

    /**
     * Listeners for layout change events.
     */
    private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;

    protected OnScrollChangeListener mOnScrollChangeListener;

    /**
     * Listeners for attach events.
     */
    private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;

    /**
     * Listener used to dispatch click events.
     * This field should be made private, so it is hidden from the SDK.
     * {@hide}
     */
    public OnClickListener mOnClickListener;

    /**
     * Listener used to dispatch long click events.
     * This field should be made private, so it is hidden from the SDK.
     * {@hide}
     */
    protected OnLongClickListener mOnLongClickListener;

    /**
     * Listener used to dispatch context click events. This field should be made private, so it
     * is hidden from the SDK.
     * {@hide}
     */
    protected OnContextClickListener mOnContextClickListener;

    /**
     * Listener used to build the context menu.
     * This field should be made private, so it is hidden from the SDK.
     * {@hide}
     */
    protected OnCreateContextMenuListener mOnCreateContextMenuListener;

    private OnKeyListener mOnKeyListener;

    private OnTouchListener mOnTouchListener;

    private OnHoverListener mOnHoverListener;

    private OnGenericMotionListener mOnGenericMotionListener;

    private OnDragListener mOnDragListener;

    private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;

    OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
}

定义的全都是Listener!包括OnClickListener,OnTouchListener等等。这么说来,ListenerInfo的作用就是为外界提供接口信息。而如果我们设置了Listener,比如setOnTouchListener:

/**
 * Register a callback to be invoked when a touch event is sent to this view.
 * @param l the touch listener to attach to this view
 */
public void setOnTouchListener(OnTouchListener l) {
    getListenerInfo().mOnTouchListener = l;
}

按照我们上面的分析,getListenerInfo()在mListenerInfo不为空的时候会new一个新值,所以当你调用了setOnTouchListener的时候,mListenerInfo就已经是不为空了。
我们看看第27行的判断

if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}

if中有四个条件,只有其中一个不满足,就会进行33行的判断
第一个条件:只要设置了listener,那么li不为空。
第二个条件:因为我们调用了setOnTouchListener,所以li.mOnTouchListener也不为空。
第三个条件:mViewsFlags已经分析过了,是包含该View标识的变量,ENABLED_MASK的注释说明了这个View是否是ENABLE的(按钮默认是enable的,如果不是enable的话,那么当你点击的时候,按钮就不会产生响应)
第四个条件:onTouch的返回值是否为true

在我们的案例中,我们的按钮设置了onTouchListener,所以四个判断可以缩短成一个,也就是

if(li.mOnTouchListener.onTouch(this, event))
    result = true;

看到没,dispatchTouchEvent的返回值最终就和我们实现onTouchListener时所实现的onTouch方法的返回值有关系了。

上面已经说过,如果result为true,表示分发,否则表示不分发。当设置onTouch返回为true时,该view也就不会继续处理下一个触摸事件了。我们先试试看,在Button的onTouch设置为true,会出现什么情况。

可以发现,我们的onTouch只处理了DOWN的event,而不再响应其他的event了,甚至就连onClick方法也不再执行。

可是,我们只是改变了onTouch的返回值,为什么会影响到onClick方法呢?

继续查看dispatchTouchEvent的源码,在27行以后的第二个if,也就是33行的if判断:

 if (!result && onTouchEvent(event)) {
            result = true;
  }

如果onTouch返回的是true,会导致!result为false,不对后面的条件进行判断,从而进不去该if语句内部。而后面的条件为onTouchEvent(event)的返回值。onTouch为true,该条件不判断,而onClick也不执行,是不是可以说其实在onTouchEvent内部可能存在onClick语句?

我们进入到onTouchEvent的内部看看

public boolean onTouchEvent(MotionEvent event) {
    final float x = event.getX();
    final float y = event.getY();
    final int viewFlags = mViewFlags;
    final int action = event.getAction();

    if ((viewFlags & ENABLED_MASK) == DISABLED) {
        if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
            setPressed(false);
        }
        // A disabled view that is clickable still consumes the touch
        // events, it just doesn't respond to them.
        return (((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
    }

    if (mTouchDelegate != null) {
        if (mTouchDelegate.onTouchEvent(event)) {
            return true;
        }
    }

    if (((viewFlags & CLICKABLE) == CLICKABLE ||
            (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
            (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
        switch (action) {
            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, x, y);
                   }

                    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.
                            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();
                }
                mIgnoreNextUpEvent = false;
                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();
                    }
                    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);
                }
                break;

            case MotionEvent.ACTION_CANCEL:
                setPressed(false);
                removeTapCallback();
                removeLongPressCallback();
                mInContextButtonPress = false;
                mHasPerformedLongPress = false;
                mIgnoreNextUpEvent = false;
                break;

            case MotionEvent.ACTION_MOVE:
                drawableHotspotChanged(x, y);

                // 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;
}

第59行有个和click名称类似的方法,我们点进去看看

public boolean performClick() {
    final boolean result;
    final ListenerInfo li = mListenerInfo;
    if (li != null && li.mOnClickListener != null) {
        playSoundEffect(SoundEffectConstants.CLICK);
        li.mOnClickListener.onClick(this);
        result = true;
    } else {
        result = false;
    }

    sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
    return result;
}

果然,这个方法内部,就是调用了ListenerInfo的OnClickListener实例的onClick方法。那么除了if (!result && onTouchEvent(event)),剩余的代码(dispatchTouchEvent的38行以后)会去调用onClick方法吗?

依次点进各个方法的内部,并没有发现和onClick有关的代码。所以可以肯定,onClick方法必然是在onTouchEvent里面调用,且在dispatchTouchEvent方法内部,只有它一个方法调用了onClick方法。我们也能通过反证法进行验证:假设后续的方法也调用了onClick的话,那么Log打印的onClick应该不止一次,但是Log打印的onClick方法有且仅有一次,所以假设有误,也就是只执行了一次onClick方法,而该方法正是在onTouchEvent内部。

不过在此之前,我们先对dispatchTouchEvent进行简化,根据上面的分析,简化后的代码为:

public boolean dispatchTouchEvent(MotionEvent event) {

if (!isAccessibilityFocusedViewOrHost()) 
    return false;

boolean result = false;

ListenerInfo li = mListenerInfo;

if(li.mOnTouchListener.onTouch(this, event))
    result = true;
else if(onTouchEvent(event)) 
    result = true;

return result;

}

是不是感觉清晰许多了?实际上,当我们onTouch返回false的时候,就会去执行onTouchEvent。

我们继续分析onTouchEvent方法。

在分析前,我们再明确一下onTouch返回值对dispatchTouchEvent造成的影响:
onTouch返回为false,所以result仍然为false。所以,result的值取决于onTouchEvent的返回值,也正好与onTouchEvent返回值相同。如果onTouchEvent返回true,则分发事件,否则不分发事件。

那么,分析开始。
第2-5行,初始化变量:点击的坐标,view的标志,event的动作

第7行的判断:

if ((viewFlags & ENABLED_MASK) == DISABLED) {
        if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
            setPressed(false);
        }
        // A disabled view that is clickable still consumes the touch
        // events, it just doesn't respond to them.
        return (((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
}

如果view是disabled的,且是clickable的,则返回true,如果是disclickable的,则返回false。

如果view是enable的,则进入第17行的判断:

if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
}

mTouchDelegate是的Touch事件进行代理处理(比如说,点击A按钮,但是A按钮不做处理,反而是让B按钮来处理触摸事件)。一般情况下是false,所以不会进入该if语句。

这个if判断以后的大段代码里,只有两行代码是和return有关的,分别为133行return true和136行return false,而133行在第23行的if条件判断内部最后一行语句。也就是说,如果进了if,则返回true,分发事件,否则返回false,不分发事件。

进入23行代码:

if (((viewFlags & CLICKABLE) == CLICKABLE ||
            (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
            (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
        switch (action) {
            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, x, y);
                   }

                    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.
                            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();
                }
                mIgnoreNextUpEvent = false;
                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();
                    }
                    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:
                setPressed(false);
                removeTapCallback();
                removeLongPressCallback();
                mInContextButtonPress = false;
                mHasPerformedLongPress = false;
                mIgnoreNextUpEvent = false;
                break;

            case MotionEvent.ACTION_MOVE:
                drawableHotspotChanged(x, y);

                // 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;
    }

看上去似乎很长,不过大部分的代码不是我们分析重点,我们只需要重点关注该方法的返回值和onClick事件的触发就可以了。因为①返回值是dispatchTouchEvent事件分发的关键,②onClick事件则是为了验证该事件是在onTouch事件后调用,③并且当onTouch返回true的时候不会再调用onClick。
②③已经分析过了,所以只需要验证①,基本上就能理解view的事件分发机制,看看①,也就是23行代码的开始:

if (((viewFlags & CLICKABLE) == CLICKABLE ||
            (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
            (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {

第一行,在view已经是enable的状态下,判断是不是clickable,如果是clickable的话,进入if语句,最后会返回true,否则直接返回false。①②③都验证完成了。

对于onTouchEvent方法,我们进行简化,简化后的代码如下:

    public boolean onTouchEvent(MotionEvent event) {
        if ((viewFlags & ENABLED_MASK) == DISABLED) {

            return (((viewFlags & CLICKABLE) == CLICKABLE
                                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
                }
        if (((viewFlags & CLICKABLE) == CLICKABLE ||
                        (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
                        (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
            switch(event){
                case MotionEvent.ACTION_UP:
                    li.mOnClickListener.onClick(this);
            }
            return true;
        }

        return false;
    }

这是第一步简化,但通常情况下,我们不需要设置长按和上下文点击(上下文点击用于压感式屏幕或者鼠标右键等等),所以我们能进行第二步的简化:

    public boolean onTouchEvent(MotionEvent event) {
        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            return ((viewFlags & CLICKABLE) == CLICKABLE);
        }
        if ((viewFlags & CLICKABLE) == CLICKABLE) {
            switch(event){
                case MotionEvent.ACTION_UP:
                    li.mOnClickListener.onClick(this);
            }
            return true;
        }
        return false;
    }

是不是简单许多了?其实onTouchEvent只有在enable并且clickable的时候才返回true,其他情况下才返回false。而在onTouchEvent里,又会去调用onClick方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值