基于SDK32,Android12,关于应用启动的大致流程,请参考android 应用启动流程(一) - 简书 (jianshu.com)
这一篇主要梳理以下几个问题
- setContentView干了什么
- DectorView是什么
- 界面和Window有什么关系
setContentView干了什么
setContentView会在oncreate的时候塞入一个布局,其实就是解析加载布局
首先会在Activity.java中看下setContentView代码
Activity.java
//这个window其实就是PhoneWindow,那就是得去看看Phonewindow如何
//实现得setContentView
//这个mWindow的初始化实在HandleLaunchActivity,进行attach的时候进行的,
//也就是在调用onCreate之前,就已经完成实例
mWindow = new PhoneWindow(this, window, activityConfigCallback);
public Window getWindow() {
return mWindow;
}
/**
* Set the activity content from a layout resource. The resource will be
* inflated, adding all top-level views to the activity.
*
* @param layoutResID Resource ID to be inflated.
*
* @see #setContentView(android.view.View)
* @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
*/
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
接下来看看PhoneWindow得操作,比较重要的是mContentParent 、DecorView、Inflate,着重看下注释
PhoneWindow.java
@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) {
//创建DecorView以及mContentParent
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;
}
PhoneWindow操作主要两件事情:
- //创建DecorView以及mContentParent
- //进行布局递归实例
先看下第一件事情 创建DecorView以及mContentParent
创建DecorView
private void installDecor() {
if (mDecor == null) {
//生产DecorView
mDecor = generateDecor(-1);
mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
mDecor.setIsRootNamespace(true);
if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
}
} else {
mDecor.setWindow(this);
}
if (mContentParent == null) {
//生产mContentParent,但是基于Decorview
mContentParent = generateLayout(mDecor);
}
...................省略code .....................
}
//DecorView其实就是一个帧布局(Framelayout)
/** @hide */
public class DecorView extends FrameLayout implements RootViewSurfaceTaker, WindowCallbacks
//生产Decorview也比较简单主要是content和phonewindow关联
protected DecorView generateDecor(int featureId) {
// System process doesn't have application context and in that case we need to directly use
// the context we have. Otherwise we want the application context, so we don't cling to the
// activity.
Context context;
if (mUseDecorContext) {
Context applicationContext = getContext().getApplicationContext();
if (applicationContext == null) {
context = getContext();
} else {
context = new DecorContext(applicationContext, this);
if (mTheme != -1) {
context.setTheme(mTheme);
}
}
} else {
context = getContext();
}
//实例,这个时候还没有内容,空布局和Phonewindow绑定
return new DecorView(context, featureId, this, getAttributes());
}
创建mContentParent,并将mDecor和mContentParent产生关联
//注意入参是DecorView
protected ViewGroup generateLayout(DecorView decor) {
.................省略N行,都是根据window特征进行判断,寻找合适得布局(系统提供的初步布局)....................................
} else {
// Embedded, so no decoration is needed.
//如果没有特殊的window配置,一般会进行通用布局,这也是为啥window属性配置要在setContentView之前设置
layoutResource = R.layout.screen_simple;
// System.out.println("Simple!");
}
mDecor.startChanging();
//将布局加载到mDecor中
mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
//mContentparent 初始化地方,就是拿到的是content得那个view
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
if (contentParent == null) {
throw new RuntimeException("Window couldn't find content container view");
}
附上R.layout.screen_simple代码
/frameworks/base/core/res/res/layout/screen_simple.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<ViewStub android:id="@+id/action_mode_bar_stub"
android:inflatedId="@+id/action_mode_bar"
android:layout="@layout/action_mode_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="?attr/actionBarTheme" />
<FrameLayout
android:id="@android:id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foregroundInsidePadding="false"
android:foregroundGravity="fill_horizontal|top"
android:foreground="?android:attr/windowContentOverlay" />
</LinearLayout>
至此DecorView和mContentParent已经配置欧ok
DecorView---就是我们的跟布局,也就是上面得screen_simple.xml
mContentParent---就是上面布局中得 android:id="@android:id/content"这个view
第二件事情 自定义布局递归实例
在上面讲过,Phonewindow得setContentVIew中,得到DecorView和mContentParent后就会进行对自定义布局得inflate
//进行布局递归实例
mLayoutInflater.inflate(layoutResID, mContentParent);
我们继续看看这个代码
//注意inflate第三个参数 attachToRoot,自定义得肯定是true,系统得是false,
//其实在DecorView加载系统布局得时候,也是inflate,其中就是false
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}
View view = tryInflatePrecompiled(resource, res, root, attachToRoot);
if (view != null) {
return view;
}
XmlResourceParser parser = res.getLayout(resource);
try {
//拿到parser之后,进行布局解析
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
//继续跟一下看看
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
.......................省略代码....................
//这里有个判断,tag是merge,就直接不去加载自定义得根布局
if (TAG_MERGE.equals(name)) {
if (root == null || !attachToRoot) {
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
rInflate(parser, root, inflaterContext, attrs, false);
} else {
// Temp is the root view that was found in the xml
//这里也可以看到是tag实例为具体得view
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
// Inflate all children under temp against its context.
//遍历子布局
rInflateChildren(parser, temp, attrs, true);
if (DEBUG) {
System.out.println("-----> done inflating children");
}
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
//add整个布局到mContentParent
if (root != null && attachToRoot) {
root.addView(temp, params);
}
最终遍历子布局,递归就有可能会有stackOVerflow,这也是不能嵌套太多,当然一般嵌套几千层没什么问题,但是效率堪忧,取决于栈帧大小
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
final int depth = parser.getDepth();
int type;
boolean pendingRequestFocus = false;
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
final String name = parser.getName();
if (TAG_REQUEST_FOCUS.equals(name)) {
pendingRequestFocus = true;
consumeChildElements(parser);
} else if (TAG_TAG.equals(name)) {
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge /> must be the root element");
} else {
//每个TAg都会创建view
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
//递归来了,
rInflateChildren(parser, view, attrs, true);
viewGroup.addView(view, params);
}
}
if (pendingRequestFocus) {
parent.restoreDefaultFocus();
}
if (finishInflate) {
parent.onFinishInflate();
}
}
至此布局view全部创建ok,其中要注意的是,自定义view,两个参数得构造函数为必须,这是因为在创建view得时候,反射用到的就是两个参数的
@UnsupportedAppUsage
static final Class<?>[] mConstructorSignature = new Class[] {
Context.class, AttributeSet.class};
总结一下
至此,oncreate得基本逻辑已经清晰,回顾下三个问题
- setContentView干了什么
创建PhoneWindow并加载自定义布局,创建根布局DecorView,并遍历布局,实例View - DectorView是什么
界面根布局 - 界面和Window有什么关系
window会影响根布局,window配置决定了界面得基本显示