Android笔记 触摸事件分发过程

1、触摸事件触发后,先会传到Activity的dispatchTouchEvent

public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        //如果Window的superDispatchTouchEvent返回true,说明事件被消费  
        //如果返回false,则由Activity自身消费,即调用其onTouchEvent方法
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

2、getWindow()返回的是PhoneWindow对象,在PhoneWindow中又对调用Decorview的superDispatchTouchEvent, Decorview继承FrameLayout,FrameLayout继承自ViewGroup。
总结:getWindow().superDispatchTouchEvent(),作用是将触屏事件继续传递到ViewGroup层中。

final void attach(Context context, ActivityThread aThread,
            Instrumentation instr, IBinder token, int ident,
            Application application, Intent intent, ActivityInfo info,
            CharSequence title, Activity parent, String id,
            NonConfigurationInstances lastNonConfigurationInstances,
            Configuration config) {
        ...
        mWindow = PolicyManager.makeNewWindow(this);
}

//PolicyManager.java
public static Window makeNewWindow(Context context) {
    return sPolicy.makeNewWindow(context);
} 
//Policy
public Window makeNewWindow(Context context) {
    return new PhoneWindow(context);
} 

//PhoneWindow.java
public boolean superDispatchTouchEvent(MotionEvent event) {
    return mDecor.superDispatchTouchEvent(event);
}

//Decorview.java
public boolean superDispatchTouchEvent(MotionEvent event) {
    return super.dispatchTouchEvent(event);
}

3、在ViewGroup中会调用onInterceptTouchEvent方法,它是拦截触摸事件的接口。这个方法只有在ViewGroup中才有,如果ViewGroup不想将触摸事件传递给它的子View,则可以在onInterceptTouchEvent中进行拦截。返回值:true,表示ViewGroup拦截了该触摸事件;那么,该事件就不会分发给它的子View。否则,表示ViewGroup没有拦截该事件,该事件就会分发给它的子View。
4、如果ViewGroup不拦截该触摸事件,则会将该触摸事件递归分发给ViewGroup的子View。如果子View是ViewGroup类型,则会把事件递归到孩子的孩子。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容