前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android--事件分发机制(一)

Android--事件分发机制(一)

作者头像
aruba
发布2020-07-03 11:18:59
6440
发布2020-07-03 11:18:59
举报
文章被收录于专栏:android技术android技术
在安卓中如果我们需要点击一个控件,并做处理的话,首先想到的就是setOnClickListener方法和setOnTouchListener方法,而在自定义控件中,需要自己处理触摸事件的话,我们需要改写onTouchEvent方法。这些方法的执行顺序和怎么被调用的,就是今天的研究课题
首先自定义一个控件,并改写onTouchEvent方法,打印日志
代码语言:javascript
复制
/**
 * 测试事件分发顺序
 */
public class MyView extends View {
    public static final String TAG = MyView.class.getSimpleName();

    public MyView(Context context) {
        this(context, null);
    }

    public MyView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.i(TAG, "onTouchEvent  " + event.getAction());
        return super.onTouchEvent(event);
    }
}
代码语言:javascript
复制
public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MyView my_test = findViewById(R.id.my_test);
        
        my_test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(MyView.TAG, "onClick");
            }
        });
        my_test.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.i(MyView.TAG, "onTouch  "+event.getAction());
                return false;
            }
        });
    }
}
打印日志如下:
代码语言:javascript
复制
2020-02-08 16:09:51.594 11907-11907/com.aruba.touchapplication I/MyView: onTouch  0
2020-02-08 16:09:51.595 11907-11907/com.aruba.touchapplication I/MyView: onTouchEvent  0
2020-02-08 16:09:51.610 11907-11907/com.aruba.touchapplication I/MyView: onTouch  2
2020-02-08 16:09:51.610 11907-11907/com.aruba.touchapplication I/MyView: onTouchEvent  2
2020-02-08 16:09:51.637 11907-11907/com.aruba.touchapplication I/MyView: onTouch  2
2020-02-08 16:09:51.637 11907-11907/com.aruba.touchapplication I/MyView: onTouchEvent  2
2020-02-08 16:09:51.639 11907-11907/com.aruba.touchapplication I/MyView: onTouch  1
2020-02-08 16:09:51.639 11907-11907/com.aruba.touchapplication I/MyView: onTouchEvent  1
2020-02-08 16:09:51.641 11907-11907/com.aruba.touchapplication I/MyView: onClick
查看源码发现,0代表按下,1代表抬起,2代表移动
代码语言:javascript
复制
public static final int ACTION_DOWN             = 0;
public static final int ACTION_UP               = 1;
public static final int ACTION_MOVE             = 2;
所以一个控件触摸事件的顺序是先调用onTouch方法,再调用onTouchEvent方法,最后调用onClick方法,至于原因,接下来我们将分析源码
我们来到View的dispatchTouchEvent方法
代码语言:javascript
复制
    /**
     * 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) {
        //AccessibilityService是辅助残疾人士使用手机的功能,可以模拟触摸事件,首先在事件分发前,
        //会判断是否是模拟触摸事件
        // 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();
        }

        //安全检测,一般都是true
        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            //这边会判断是否设置了OnTouchListener,如果设置了,并在回调时返回了ture,将result赋值成true
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }

            //如果上面result为true了(mOnTouchListener.onTouch方法返回true),则不会调用onTouchEvent方法
            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;
    }
在这边我们发现,View会先调用OnTouchListener的onTouch方法,然后再调用OnTouchEvent方法,再看OnTouchEvent方法
代码语言:javascript
复制
    public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();

        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                setPressed(false);
            }
            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
            return clickable;
        }
        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }

        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
                case MotionEvent.ACTION_UP:
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
                        handleTooltipUp();
                    }
                    if (!clickable) {
                        removeTapCallback();
                        removeLongPressCallback();
                        mInContextButtonPress = false;
                        mHasPerformedLongPress = false;
                        mIgnoreNextUpEvent = false;
                        break;
                    }
                    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)) {
                                    performClickInternal();
                                }
                            }
                        }

                        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:
                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
                    }
                    mHasPerformedLongPress = false;

                    if (!clickable) {
                        checkForLongClick(0, x, y);
                        break;
                    }

                    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:
                    if (clickable) {
                        setPressed(false);
                    }
                    removeTapCallback();
                    removeLongPressCallback();
                    mInContextButtonPress = false;
                    mHasPerformedLongPress = false;
                    mIgnoreNextUpEvent = false;
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    break;

                case MotionEvent.ACTION_MOVE:
                    if (clickable) {
                        drawableHotspotChanged(x, y);
                    }

                    // Be lenient about moving outside of buttons
                    if (!pointInView(x, y, mTouchSlop)) {
                        // Outside button
                        // Remove any future long press/tap checks
                        removeTapCallback();
                        removeLongPressCallback();
                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                            setPressed(false);
                        }
                        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    }
                    break;
            }

            return true;
        }

        return false;
    }
发现在MotionEvent.ACTION_UP时,会调用到performClickInternal方法,而performClickInternal方法就是调用了performClick方法
代码语言:javascript
复制
    private boolean performClickInternal() {
        // Must notify autofill manager before performing the click actions to avoid scenarios where
        // the app has a click listener that changes the state of views the autofill service might
        // be interested on.
        notifyAutofillManagerOnClick();

        return performClick();
    }
代码语言:javascript
复制
    public boolean performClick() {
        // We still need to call this method to handle the cases where performClick() was called
        // externally, instead of through performClickInternal()
        notifyAutofillManagerOnClick();

        final boolean result;
        final ListenerInfo li = mListenerInfo;
        //如果mOnClickListener不为空,则调用mOnClickListener的onClick方法
        ///mOnClickListener就是我们调用setOnClickListener传入的参数
        if (li != null && li.mOnClickListener != null) {
            playSoundEffect(SoundEffectConstants.CLICK);
            li.mOnClickListener.onClick(this);
            result = true;
        } else {
            result = false;
        }

        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);

        notifyEnterOrExitForAutoFillIfNeeded(true);

        return result;
    }
到此,我们知道了为什么onTouch会先执行,onTouchEvent会后执行,并且为什么手指抬起后才会执行onClick方法
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 在安卓中如果我们需要点击一个控件,并做处理的话,首先想到的就是setOnClickListener方法和setOnTouchListener方法,而在自定义控件中,需要自己处理触摸事件的话,我们需要改写onTouchEvent方法。这些方法的执行顺序和怎么被调用的,就是今天的研究课题
  • 首先自定义一个控件,并改写onTouchEvent方法,打印日志
  • 打印日志如下:
  • 查看源码发现,0代表按下,1代表抬起,2代表移动
  • 所以一个控件触摸事件的顺序是先调用onTouch方法,再调用onTouchEvent方法,最后调用onClick方法,至于原因,接下来我们将分析源码
  • 我们来到View的dispatchTouchEvent方法
  • 在这边我们发现,View会先调用OnTouchListener的onTouch方法,然后再调用OnTouchEvent方法,再看OnTouchEvent方法
  • 发现在MotionEvent.ACTION_UP时,会调用到performClickInternal方法,而performClickInternal方法就是调用了performClick方法
  • 到此,我们知道了为什么onTouch会先执行,onTouchEvent会后执行,并且为什么手指抬起后才会执行onClick方法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档