Android View事件分发机制(源码分析)

android事件处理涉及到的三个重要函数

事件分发:public boolean dispatchTouchEvent(MotionEvent ev)

由外部View接收,然后依次传递给其内层View

事件拦截:public boolean onInterceptTouchEvent(MotionEvent ev)

从最内View单元(事件源)开始依次向外层传递

事件响应:public boolean onTouchEvent(MotionEvent ev)

复杂性表现在:

可以控制每层事件是否继续传递(分发和拦截协同实现),以及事件的具体消费(事件分发也具有事件消费能力)。

三个函数所处位置

Activity 包含 dispatchTouchEventonTouchEvent方法(API 25):

    /**
     * Called to process touch screen events.  You can override this to
     * intercept all touch screen events before they are dispatched to the
     * window.  Be sure to call this implementation for touch screen events
     * that should be handled normally.
     *
     * @param ev The touch screen event.
     *
     * @return boolean Return true if this event was consumed.
     */
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    /**
     * Called when a touch screen event was not handled by any of the views
     * under it.  This is most useful to process touch events that happen
     * outside of your window bounds, where there is no view to receive it.
     *
     * @param event The touch screen event being processed.
     *
     * @return Return true if you have consumed the event, false if you haven't.
     * The default implementation always returns false.
     */
    public boolean onTouchEvent(MotionEvent event) {
        if (mWindow.shouldCloseOnTouch(this, event)) {
            finish();
            return true;
        }

        return false;
    }

ViewGroup包含dispatchTouchEventonInterceptTouchEvent方法。

View包含 dispatchTouchEventonTouchEvent方法。

点击Button按钮时:

硬件触发

--> Activity示例(如LoginAcvtivity).dispatchTouchEvent --> Activity.dispatchTouchEvent

--> ViewGroup.dispatchTouchEvent --> ViewGroup.onInterceptTouchEvent

--> View.dispatchTouchEvent --> View.onTouchEvent

中间还有 DecorView.dispatchTouchEventPhoneView.superDispatchTouchEventDecorView.superDispatchTouchEvent被触发,因为他们在Activity和ViewGrounp之间。

image.png

参考:

Android View事件分发机制源码分析

Android事件分发机制源码解析

Android事件分发机制完全解析,带你从源码的角度彻底理解(上)

Android事件分发机制完全解析,带你从源码的角度彻底理解(下)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容