在日常的开发过程中我们知道通过setContentView()就能将我们自己的布局加载在屏幕之上,今天我们的目的是通过源码来分析setContentView中到底是通过何种方式将我们的UI显示出来的。
通过源码分析setContentView实际的实现是进入到了Window的实现类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 crystalized. Do not check the feature
// before this happens.
if (mContentParent == null) {
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
transitionTo(newScene);
} else {
mLayoutInflater.inflate(layoutResID, mContentParent);
}
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
mContentParentExplicitlySet = true;
}
通过该方法我们可以看出它主要是做了两件事,一是:InstallDecor,二是inflate。
1.首先让我们看看installDecor这个方法:
在该方法中主要做了两件事:一个生成mDecor和mContentParent两个对象,那么这两个对象具体是什么呢,通过对着两个对象的注释我们可以看出:
// This is the top-level view of the window, containing the window decor.
// 它是窗口的顶层View,包含decor
private DecorView mDecor;
// This is the view in which the window contents are placed. It is either
// mDecor itself, or a child of mDecor where the contents go.
// 这是窗口内容放置的位置,它要么是mDecor本身要么是mDecor子类的内容
ViewGroup mContentParent;
一个是代表着窗口的顶层view,一个是用来装他视图的内容。其中generateDecor只是创建了一个DecorView(extends FrameLayout)实体,继续进入generateLayout.其中调用了大量设置window特性的requestFeature方法,
从此我们不难看出,在我们平时设置的getWindow.requestFeature的方法实际是在setContentView中实现的,这也是为什么该方法要在setContentView之前调用的原因。继续往下看:
终于我们找到和前文有关的东西,“Inflate the window decor” 在这里通过features加载了一个系统提前写好的布局,并传入给了DecorView。在这里我们看一下这个系统布局screen_simple里面究竟写了什么:
通过布局上的注释,以及源码分析DecorView 和自己布局的关系如下图所示:
从上面对DecorView源码的查看我们知道DecorView是继承于FrameLayout,它通过加载一个系统布局将自己的布局加载在FrameLayout中,渲染出了屏幕上我们所见的视图。
2.mLayoutInflater.inflate方法
inflate方法是我们比较熟悉的方法,它主要用于解析我们的xml布局,详细的解析流程如下图:
由上可知,我们知道了setContentView主要做了两件事,一是加载环境配置,二是加载自己的布局。