#Android View是如何被添加到窗口上?
2020-03-22 本文已影响0人
刘小厨
我们看下布局加载的入口
说明:本文讲的Activity为
不同于
,翻源码的同学注意下~
Activity->onCreate()-> setContentView();
其中方法调用了 getWindow().setContentView(layoutResID);
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
方法返回的是
对象
是一个抽象类,存在唯一实现
所以我们看下的
方法都做了什么,代码如下:
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;
}
这里主要做了两件事
-
方法初始化
-
解析布局资源文件
第一步
在这个方法里如果
==
创建一个实例
创建之后,调用
根据系统主题性加载配置不同的系统布局资源文件(例:
),将布局资源文件inflate后,添加到
中
注: 继承
第二步,其实就是将传进来的contentView布局资源文件Id解析,添加到DecorView中的基础布局文件的FrameLayout中,及findViewById找到id为
的FrameLayout
附上几个关键类的关系图:
![](https://img.haomeiwen.com/i11952059/95d0a4724d2f8e93.png)
附上视图结构图:
![](https://img.haomeiwen.com/i11952059/14b6c1cc4ad28b0e.png)