setOnTouchListener onTouchEvent setOnLongClickListener setOnClickListener 執行順序及源碼分析

1.先說 setOnClickListener   setOnTouchListener   onTouchEvent 

1. 1先看運行結果  :

  MyViewGroup-->dispatchTouchEvent-->ACTION_DOWN

MyViewGroup-->onInterceptTouchEvent-->ACTION_DOWN

MyButton-->dispatchTouchEvent-->ACTION_DOWN

MyButton-->setOnTouchListener-->ACTION_DOWN

MyButton-->onTouchEvent-->ACTION_DOWN

MyViewGroup-->dispatchTouchEvent-->ACTION_UP

MyViewGroup-->onInterceptTouchEvent-->ACTION_UP

MyButton-->dispatchTouchEvent-->ACTION_UP

setOnTouchListener-->ACTION_UP

MyButton-->onTouchEvent-->ACTION_UP

MyButton-->setOnClickListener

1.2 源碼分析

   1.先看setOnLongClickListener方法

public void setOnLongClickListener(@Nullable OnLongClickListener l) {
    if (!isLongClickable()) {
        setLongClickable(true);
    }
    getListenerInfo().mOnLongClickListener = l;
}
public interface OnLongClickListener {
  
    boolean onLongClick(View v);
}

看到我們實例化的接口賦值給了mOnLongClickListener  ,好這就夠了,如果好奇getListenerInfo(),自己可以去了解下。

 2.再看 setOnClickListener

public void setOnClickListener(@Nullable OnClickListener l) {
    if (!isClickable()) {
        setClickable(true);
    }
    getListenerInfo().mOnClickListener = l;
}

其實和setOnLongClickListener差不多 知道mOnClickListener 就行了。

3. setOnTouchListener

public void setOnTouchListener(OnTouchListener l) {
    getListenerInfo().mOnTouchListener = l;
}
public interface OnTouchListener {
    boolean onTouch(View v, MotionEvent event);
}

注意onTouch 是有返回值的,這點很重要。

4.再來看下 先從 MyButton-->dispatchTouchEvent 開始分析

  

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)) {
        if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
            result = true;
        }
        //noinspection SimplifiableIfStatement
        // 這裏是重點,當我們執行mOnTouchListener.onTouch 監聽的 setOnTouchListener 的onTouch 返回值爲true 時 result 賦值爲true ,這裏先執行了setOnTouchListener  方法
        ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnTouchListener != null
                && (mViewFlags & ENABLED_MASK) == ENABLED
                && li.mOnTouchListener.onTouch(this, event)) {
            result = true;
        }
       //當 result 爲true是 onTouchEvent 就不會執行了,這就是我上邊說的,返回值很重要,監聽的setOnTouchListener 消耗掉了本次事件,onTouchEvent不會執行,那麼setOnClickListener呢,當然就不會執行了,我們分析下onTouchEvent(event)就知道了。
        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;
}

5.onTouchEvent(event) 與 setOnClickListener 執行關係

onTouchEvent(event)源碼分析 
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, 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;
    }

    return false;
}

接着看

performClick() 的實現方式
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;
}

在這裏我們終於找到了mOnClickListener.onClick   方法,現在我們應該知道這幾個之間的關係了吧。

總結:最先執行setOnTouchListener  然後執行onTouchEvet  緊接着在onTouchEvet中執行了setOnClickListener ,當然如果setOnTouchtListener 返回了true 那麼後邊兩部就都不會執行了。

2. setOnLongClickListener setOnTouchListener   onTouchEvent 

2.1執行順序 結果

11-16 15:03:15.699 20721-20721/com.example.macbook.demoproject2 I/System.out: ------>MyViewGroup-->dispatchTouchEvent-->ACTION_DOWN
11-16 15:03:15.699 20721-20721/com.example.macbook.demoproject2 I/System.out: ------>MyViewGroup-->onInterceptTouchEvent-->ACTION_DOWN
11-16 15:03:15.699 20721-20721/com.example.macbook.demoproject2 I/System.out: ------>MyButton-->dispatchTouchEvent-->ACTION_DOWN
11-16 15:03:15.699 20721-20721/com.example.macbook.demoproject2 I/System.out: MainActivity-->setOnTouchListener-->ACTION_DOWN
11-16 15:03:15.699 20721-20721/com.example.macbook.demoproject2 I/System.out: ------>MyButton-->onTouchEvent-->ACTION_DOWN
11-16 15:03:16.200 20721-20721/com.example.macbook.demoproject2 I/System.out: MainActivityonLongClick: setOnLongClickListener
11-16 15:03:16.996 20721-20721/com.example.macbook.demoproject2 I/System.out: ------>MyViewGroup-->dispatchTouchEvent-->ACTION_UP
11-16 15:03:16.996 20721-20721/com.example.macbook.demoproject2 I/System.out: ------>MyViewGroup-->onInterceptTouchEvent-->ACTION_UP
11-16 15:03:16.996 20721-20721/com.example.macbook.demoproject2 I/System.out: ------>MyButton-->dispatchTouchEvent-->ACTION_UP
11-16 15:03:16.997 20721-20721/com.example.macbook.demoproject2 I/System.out: MainActivity-->setOnTouchListener-->ACTION_UP
11-16 15:03:16.997 20721-20721/com.example.macbook.demoproject2 I/System.out: ------>MyButton-->onTouchEvent-->ACTION_UP

這次我把詳細的log粘出來了,先看兩個節點時間

1. MyViewGroup-->dispatchTouchEvent-->ACTION_DOWN 到  setOnLongClickListener

11-16 15:03:15.699   -----------------》 11-16 15:03:16.200 從按下到觸發長按事件的時間

2.setOnLongClickListener  到  MyViewGroup-->dispatchTouchEvent-->ACTION_UP

11-16 15:03:16.200 ----------------------》11-16 15:03:16.996 這個是觸發長按事件到我手指擡起觸發父類的第一個方法時間

2.2 源碼分析

 在分析之前先有幾個問題

    1.長按事件到底啥時執行,按下後多久執行。

    2.觸發後爲啥我的點擊事件沒有了。

從MyButton-->onTouchEvent   ACTION_DOWN 開始分析

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

    return false;
}

我們在 ACTION_DOWN  中看到checkForLongClick(0, x, y)方法  傳入三個參數0,和x,y,接着看checkForLongClick方法

private void checkForLongClick(int delayOffset, float x, float y) {
    if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
        mHasPerformedLongPress = false;

        if (mPendingCheckForLongPress == null) {
            mPendingCheckForLongPress = new CheckForLongPress();
        }
        mPendingCheckForLongPress.setAnchor(x, y);
        mPendingCheckForLongPress.rememberWindowAttachCount();
        postDelayed(mPendingCheckForLongPress,
                ViewConfiguration.getLongPressTimeout() - delayOffset);
    }
}

CheckForLongPress 實現了 Runnable  接口,然後通過

postDelayed發送消息
public boolean postDelayed(Runnable action, long delayMillis) {
    final AttachInfo attachInfo = mAttachInfo;
    if (attachInfo != null) {
        return attachInfo.mHandler.postDelayed(action, delayMillis);
    }

    // Postpone the runnable until we know on which thread it needs to run.
    // Assume that the runnable will be successfully placed after attach.
    getRunQueue().postDelayed(action, delayMillis);
    return true;
}

其實最後調用了handler 的postDelayed間隔 delayMillis 秒後發送消息,執行Runnable中的run方法,那我們看

Runnable中是如何實現的。
private final class CheckForLongPress implements Runnable {
    private int mOriginalWindowAttachCount;
    private float mX;
    private float mY;

    @Override
    public void run() {
        if (isPressed() && (mParent != null)
                && mOriginalWindowAttachCount == mWindowAttachCount) {
            if (performLongClick(mX, mY)) {
                mHasPerformedLongPress = true;
            }
        }
    }

    public void setAnchor(float x, float y) {
        mX = x;
        mY = y;
    }

    public void rememberWindowAttachCount() {
        mOriginalWindowAttachCount = mWindowAttachCount;
    }
}

看到調用的了

performLongClick(mX, mY)方法並且, mHasPerformedLongPress = true;

再看performLongClick 幹了啥呢

public boolean performLongClick() {
    return performLongClickInternal(mLongClickX, mLongClickY);
}
private boolean performLongClickInternal(float x, float y) {
    sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);

    boolean handled = false;
    final ListenerInfo li = mListenerInfo;
    if (li != null && li.mOnLongClickListener != null) {
        handled = li.mOnLongClickListener.onLongClick(View.this);
    }
    if (!handled) {
        final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
        handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
    }
    if (handled) {
        performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
    }
    return handled;
}

到這裏終於看到了,li.mOnLongClickListener.onLongClick(View.this) 長按事件響應了,過程是有點曲折不過流程算是走完了。總結下,先從view 的

dispatchTouchEvent 然後調用了 view 的 onTouchEvent 事件,然後在ontoucheEvent的action_down中調用
checkForLongClick方法既長按事件。

回到先前提的兩個問題

問題1: 長按事件到底啥時執行我們已經知道了,但是按下後多久執行呢?

接着看:

觸發checkForLongClick(0, x, y);時傳進來第一個參數int類型的,字面意思是,延遲位移,
postDelayed(mPendingCheckForLongPress,
        ViewConfiguration.getLongPressTimeout() - delayOffset);

接着調用 postDelayed 其實後邊的 ViewConfiguration.getLongPressTimeout() - delayOffset 就是handler發送消息延遲時間,現在偏移時間爲0,那我們只要知道ViewConfiguration.getLongPressTimeout() 是多少就可以了。

public static int getLongPressTimeout() {
    return AppGlobals.getIntCoreSetting(Settings.Secure.LONG_PRESS_TIMEOUT,
            DEFAULT_LONG_PRESS_TIMEOUT);
}
private static final int DEFAULT_LONG_PRESS_TIMEOUT = 500;

默認的長按按壓時間是500毫秒,現在再看我開始打log時打出的開始到觸發長按,時間基本就是500了。

問題2:爲啥點擊事件不執行了

我們看到

MyButton-->onTouchEvent-->ACTION_UP

MyButton-->setOnClickListener

點擊事件其實是整個事件最後執行的在onTouchEvent 的ACTION_UP 後才執行了,那分析下點擊事件的觸發條件。

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();
        }
    }
}

mHasPerformedLongPress 這個好像在哪裏看到過啊,是的,就在Runnable 方法的run方法裏

@Override
public void run() {
    if (isPressed() && (mParent != null)
            && mOriginalWindowAttachCount == mWindowAttachCount) {
        if (performLongClick(mX, mY)) {
            mHasPerformedLongPress = true;
        }
    }
}

由於長按事件先執行,觸發了條件, mHasPerformedLongPress = true 所以當事件執行到action_up 時條件不滿足了。這就是爲啥有長按事件後點擊事件不會執行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章