之前有一篇文章源码分析了Activity#setContentView,但是目前我们写的Activity基本都是继承自AppCompactActivity,google也是建议继承AppCompactActivity可以提高一些兼容性,今天我们就来一探AppCompactActivity#setContentView的究竟,看看跟Activity#setContentView有何异同。
依照之前的惯例,先来看一张流程图,对整个流程有个大概的了解,便于理解后面的源码分析
好,我们从熟悉的MainActivity开始
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
跟进setContentView(R.layout.activity_main)
public void setContentView(@LayoutRes int layoutResID) {
this.getDelegate().setContentView(layoutResID);
}
getDelegate()返回的是AppCompatDelegate类型,AppCompatDelegate是一个接口,我们找到其实现类AppCompatDelegateImpl#setContentView
public void setContentView(int resId) {
this.ensureSubDecor();
ViewGroup contentParent = (ViewGroup)this.mSubDecor.findViewById(16908290);
contentParent.removeAllViews();
LayoutInflater.from(this.mContext).inflate(resId, contentParent);
this.mOriginalWindowCallback.onContentChanged();
}
这里ensureSubDecor()主要就是确保创建出SubDecor并给mSubDecor赋值,mSubDecor是一个ViewGroup,确保下面调用(ViewGroup)this.mSubDecor.findViewById(16908290)得到contentParent不会抛出异常,接着删除contentParent所有子View,然后将我们传入的resId渲染到contentParent上,好,我们继续跟进AppCompatDelegateImpl#ensureSubDecor
private void ensureSubDecor() {
if (!this.mSubDecorInstalled) {
// 看这里
this.mSubDecor = this.createSubDecor();
CharSequence title = this.getTitle();
if (!TextUtils.isEmpty(title)) {
if (this.mDecorContentParent != null) {
this.mDecorContentParent.setWindowTitle(title);
} else if (this.peekSupportActionBar() != null) {
this.peekSupportActionBar().setWindowTitle(title);