我们已经分析了View 和ViewGroup 的事件传递过程,那么Actvity是如何将 事件传递给ViewGroup的呢,我们还是通过源码来看一下
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
Activity 的dispatchTouchEvent 代码简直不能再简单了,看了一下onUserInteraction 是一个空的方法,他的介绍也比较简单,就为了方便我们收到事件后想要做一些响应可以通过它来完成,比如屏保或者多长时间没有操作进入待机状态
那么getWindow().superDispatchTouchEvent(ev) 都干了什么呢,说道这里我们必须要说一下Activity 的组成部分

PhoneWindow 是Android 系统系统中最基本的窗口,每一个Activity 都会创建一个,
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, String referrer, IVoiceInteractor voiceInteractor,
Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken) {
attachBaseContext(context);
mFragments.attachHost(null /*parent*/);
mWindow = new PhoneWindow(this, window, activityConfigCallback);
....
}
我们看到在Activity的attach 方法中创建了一个PhoneWindow,我们继续去看看PhoneWindow中是如何传递这个事件的,
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
PhoneWindow 的superDispatchTouchEvent 把他交给了mDecor ,那么mDecor是什么呢, mDecor是Activity 的真正的RootView,继承自FrameLayout,FrameLayout 就是继承自ViewGroup ,那么接下来的过程我想大家应该就可以理解了
网友评论