专栏首页android技术Android--事件分发机制(一)

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

在安卓中如果我们需要点击一个控件,并做处理的话,首先想到的就是setOnClickListener方法和setOnTouchListener方法,而在自定义控件中,需要自己处理触摸事件的话,我们需要改写onTouchEvent方法。这些方法的执行顺序和怎么被调用的,就是今天的研究课题
首先自定义一个控件,并改写onTouchEvent方法,打印日志
/**
 * 测试事件分发顺序
 */
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);
    }
}
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;
            }
        });
    }
}
打印日志如下:
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代表移动
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方法
    /**
     * 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方法
    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方法
    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();
    }
    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方法

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Android--ObjectAnimator源码分析

    (如:ObjectAnimator.ofFloat(iv, "translationY", 0f,1000f),其中0f,和1000f就是关键帧)

    aruba
  • Android--事件分发机制(二)

    aruba
  • Android--利用ItemTouchHelper实现RecyclerView的侧滑删除

    aruba
  • 聊聊nifi的BinlogEventListener

    nifi-1.11.4/nifi-nar-bundles/nifi-cdc/nifi-cdc-mysql-bundle/nifi-cdc-mysql-proce...

    codecraft
  • Android View的Touch事件分发

    事件分发的重要性我就不多说了,我们先从简到难。 先看View的Touch事件分发,我自定义一个View,重写OnTouchEvent函数,然后分别设置OnTou...

    曾大稳
  • Gym 100952I&&2015 HIAST Collegiate Programming Contest I. Mancala【模拟】

    I. Mancala time limit per test:3 seconds memory limit per test:256 megabytes inp...

    Angel_Kitty
  • 初探Burp Suite API 开发

    要使用python进行BurpSuite插件的开发需要安装Jython。下载地址:http://www.jython.org/downloads.html

    漏斗社区
  • 研究MapReduce源码之实现自定义LineRecordReader完成多行读取文件内容

    TextInputFormat是Hadoop默认的数据输入格式,但是它只能一行一行的读记录,如果要读取多行怎么办? 很简单 自己写一个输入格式,然后写一个对...

    汤高
  • R2D2算法Buffer数据结构复现

    https://mp.weixin.qq.com/s/KoFuCePBNPCXGWKpAy_wjw

    用户1908973
  • 多人部件解析

    Towards Real World Human Parsing: Multiple-Human Parsing in the Wild https://a...

    用户1148525

扫码关注云+社区

领取腾讯云代金券