本篇文章的起点是从 Activity
的 setContentView
方法说起。我先放一张加载布局的时序图,布局加载涉及的类相对比较少一些。
1. Activity#setContentView()
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
这里 getWindow()
返回的是 Window
类型的,它是一个抽象类,变量名为 mWindow
,之前看过我写的 Activity 启动流程
的应该知道,它是在 Activity
的 attach
方法中初始化的,可以看下面的代码:
Activity#attach
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) {
attachBaseContext(context);
mFragments.attachHost(null /*parent*/);
mWindow = new PhoneWindow(this, window, activityConfigCallback);
mWindow.setWindowControllerCallback(this);
mWindow.setCallback(this);
mWindow.setOnWindowDismissedCallback(this);
}
创建出实现类 PhoneWindow
,其实 Window
也只有一个实现类就是 PhoneWindow
. 接下来,就到了 PhoneWindow
的setContentView
方法中了,继续跟进。
2. PhoneWindow#setContentView
@Override
public void setContentView(int layoutResID) {
// Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
// decor, when theme attributes and the like are cr