小白都看得懂的布局加载流程

本文从Activity的setContentView()方法开始,逐步剖析布局加载过程,包括PhoneWindow如何设置视图,LayoutInflater如何解析并加载XML布局,以及在LayoutInflater.inflate()方法中的细节,如自定义控件的处理和控件创建的反射机制。
摘要由CSDN通过智能技术生成

本篇文章的起点是从 ActivitysetContentView方法说起。我先放一张加载布局的时序图,布局加载涉及的类相对比较少一些。

image.png

1. Activity#setContentView()

public void setContentView(@LayoutRes int layoutResID) {
    getWindow().setContentView(layoutResID);
    initWindowDecorActionBar();
}

这里 getWindow() 返回的是 Window 类型的,它是一个抽象类,变量名为 mWindow,之前看过我写的 Activity 启动流程的应该知道,它是在 Activityattach方法中初始化的,可以看下面的代码:

Activity#attach

final void attach(Context context, ActivityThread aThread,
        Instrumentation instr, IBinder token, int ident,
        Application application, Intent intent, ActivityInfo info,
        CharSequence title, Activity parent, String id,
        NonConfigurationInstances lastNonConfigurationInstances,
        Configuration config, String referrer, IVoiceInteractor voiceInteractor,
        Window window, ActivityConfigCallback activityConfigCallback) {
    attachBaseContext(context);

    mFragments.attachHost(null /*parent*/);

    mWindow = new PhoneWindow(this, window, activityConfigCallback);
    mWindow.setWindowControllerCallback(this);
    mWindow.setCallback(this);
    mWindow.setOnWindowDismissedCallback(this);
}

创建出实现类 PhoneWindow,其实 Window 也只有一个实现类就是 PhoneWindow. 接下来,就到了 PhoneWindowsetContentView 方法中了,继续跟进。

2. 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 cr
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值