Android UI源码解析

首先我们从activity中的oncreate中的setContentView()方法介绍:

在Window 抽象类中有三个setContentView的方法,Window类有是Activity的成员属性

PhoneWindow继承了Window 实现了setContentView方法, 在PhoneWindow类中还有内部类DecorView

DecorView继承了Framelayout 是一个具体现实View容器。

Android UI源码解析_第1张图片

在PhoneWindow中实现setContentView具体方法:

(layoutResID) {
    (== ) {
        installDecor()} (!hasFeature()) {
        .removeAllViews()}

    (hasFeature()) {
        Scene newScene = Scene.(layoutResIDgetContext())transitionTo(newScene)} {
        .inflate(layoutResID)}
    Callback cb = getCallback()(cb != && !isDestroyed()) {
        cb.onContentChanged()}
}

首先判断了mContentparent 是否为空,这个就是xml文件的根节点


mLayoutInflater.inflate(layoutResID, mContentParent);将我们的资源文件通过LayoutInflater对象转换为View树,并且添加至mContentParent视图中(其中mLayoutInflater是在PhoneWindow的构造函数中得到实例对象的LayoutInflater.from(context);)。

再来看下PhoneWindow类的setContentView(View view)方法和setContentView(View view, ViewGroup.LayoutParams params)方法源码:

(View viewViewGroup.LayoutParams params) {
    (== ) {
        installDecor()} (!hasFeature()) {
        .removeAllViews()}

    (hasFeature()) {
        view.setLayoutParams(params)Scene newScene = Scene(view)transitionTo(newScene)} {
        .addView(viewparams)}
    Callback cb = getCallback()(cb != && !isDestroyed()) {
        cb.onContentChanged()}
}

直接分析setContentView(View view, ViewGroup.LayoutParams params)方法就行,可以看见该方法与setContentView(int layoutResID)类似,只是少了LayoutInflater将xml文件解析装换为View而已,这里直接使用View的addView方法追加道了当前mContentParent而已。

所以说在我们的应用程序里可以多次调用setContentView()来显示界面,因为会removeAllViews


我们先看一下源码中LayoutInflater实例化获取的方法

LayoutInflater (Context context) {
    LayoutInflater LayoutInflater =
            (LayoutInflater) context.getSystemService(Context.)(LayoutInflater == ) {
        AssertionError()}
    LayoutInflater}
  • 获取LayoutInflater实例的三种方式:

  • // 方式1

  • // 调用Activity的getLayoutInflater()

  • LayoutInflater inflater = getLayoutInflater();

  • // 方式2

  • LayoutInflater inflater = LayoutInflater.from(context);

  • // 方式3

  • LayoutInflater inflater = LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);


你可能感兴趣的:(android,UI,setcontentview)