从源码角度分析AppCompactActivity#setContentView

之前有一篇文章源码分析了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);
             
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值