Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 如何把 XML 布局文件变成 View 树(上):从 setContentView 说起

編輯:關於 Android 程式設計

写了几周代码,我一直在琢磨一个问题:R.layout.xxx_view.xml 这样的布局文件,究竟是怎么被加载进 Android 的 View 层次结构(也就是我们常说的 View 树)里的?一边读源码一边查资料,下面把这条链路的上半段梳理清楚。

入口:Activity.setContentView

我们最早接触到的方法应该就是它了——在 onCreate() 里调用,就能把根布局显示出来。三个重载版本内部做的事情其实一样,都是转交给 Window:

public void setContentView(int layoutResID) {
    getWindow().setContentView(layoutResID);
    initActionBar();
}

public void setContentView(View view) {
    getWindow().setContentView(view);
    initActionBar();
}

public void setContentView(View view, ViewGroup.LayoutParams params) {
    getWindow().setContentView(view, params);
    initActionBar();
}

顺带一提 addContentView():命名上 set 是替换,add 是追加,调用之后原有的 View 层次结构仍然保留,只是又多加了一个 View。

Window 从哪来

Activity 里有一个 private Window mWindow 字段,由 attach() 方法在 Activity 创建过程中赋值:

mWindow = PolicyManager.makeNewWindow(this);
mWindow.setCallback(this);

Window、Activity、View 的关系

Window 是一个抽象类,封装了顶层窗口的样式与行为策略,提供了背景、标题栏、默认按键处理等标准 UI 能力。Android 中它唯一的实现是 PhoneWindow,需要窗口时就会 new 一个实例出来。每个 Activity 都关联一个 Window 对象,并在其上绘制 UI;Window 内部还有一个 mDecor 对象,它是整棵 View 树的根。

PhoneWindow 的诞生

PolicyManager 采用运行时加载的方式取得策略实现:

public final class PolicyManager {
    private static final String POLICY_IMPL_CLASS_NAME =
            "com.android.internal.policy.impl.Policy";
    private static final IPolicy sPolicy;

    static {
        Class policyClass = Class.forName(POLICY_IMPL_CLASS_NAME);
        sPolicy = (IPolicy) policyClass.newInstance();
    }

    public static Window makeNewWindow(Context context) {
        return sPolicy.makeNewWindow(context);
    }
}

而 Policy 的实现非常直白,同时它还预加载了一批 PhoneWindow 相关的类以提升性能:

public Window makeNewWindow(Context context) {
    return new PhoneWindow(context);
}

public LayoutInflater makeNewLayoutInflater(Context context) {
    return new PhoneLayoutInflater(context);
}

这也解释了为什么 context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) 拿到的总是 PhoneLayoutInflater。

PhoneWindow.setContentView 做了什么

PhoneWindow 里有两个关键成员:mDecor(窗口顶层的 DecorView)和 mContentParent(系统布局中 @android:id/content 对应的容器)。

@Override
public void setContentView(int layoutResID) {
    if (mContentParent == null) {
        installDecor();
    } else {
        mContentParent.removeAllViews();
    }
    mLayoutInflater.inflate(layoutResID, mContentParent);
    final Callback cb = getCallback();
    if (cb != null && !isDestroyed()) {
        cb.onContentChanged();
    }
}

这里能看出 setContentView 支持重复调用,效果等同于把之前的 View 层次全部丢掉重来。相比之下 addContentView() 少了 removeAllViews(),所以是纯粹的追加。

installDecor 与 generateLayout

installDecor() 负责创建 DecorView(一种特殊的 FrameLayout),并通过 generateLayout(mDecor) 初始化 mContentParent,顺带处理标题、ActionBar、分栏 ActionBar 等一系列窗口特性。

generateLayout() 前半段是从当前主题的 TypedArray 中读取属性,再调用 requestFeature()、setFlags() 等方法把窗口风格设置好;后半段则根据最终确定的 features 挑选对应的系统布局文件:

int layoutResource;
int features = getLocalFeatures();
if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
    layoutResource = com.android.internal.R.layout.screen_title_icons;
    removeFeature(FEATURE_ACTION_BAR);
} else if (...FEATURE_CUSTOM_TITLE...) {
    layoutResource = com.android.internal.R.layout.screen_custom_title;
} else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
    layoutResource = com.android.internal.R.layout.screen_title;
    // 有 ActionBar 时则是 screen_action_bar
} else {
    layoutResource = com.android.internal.R.layout.screen_simple;
}

mDecor.startChanging();
View in = mLayoutInflater.inflate(layoutResource, null);
decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
ViewGroup contentParent = (ViewGroup) findViewById(ID_ANDROID_CONTENT);
if (contentParent == null) {
    throw new RuntimeException("Window couldn't find content container view");
}
...
mDecor.finishChanging();
return contentParent;

系统布局里的那个"占位符"

无论选哪个系统布局,它们都有一个共同点:包含一个 id 为 @android:id/content 的 FrameLayout,这就是留给应用层的 placeholder,Activity 的布局从这里开始挂载。

<!-- screen_simple.xml -->
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <ViewStub android:id="@+id/action_mode_bar_stub"
        android:inflatedId="@+id/action_mode_bar"
        android:layout="@layout/action_mode_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <FrameLayout android:id="@android:id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:foregroundInsidePadding="false"
        android:foregroundGravity="fill_horizontal|top"
        android:foreground="?android:attr/windowContentOverlay" />
</LinearLayout>

screen_title.xml 结构类似,只是多了标题栏,并且 content 容器的高度设为 0dip 配 layout_weight="1",用来占满标题栏以下的剩余空间。

小结

到这里,上半段链路就通了:setContentView() → getWindow().setContentView() → installDecor() 建好 DecorView 与 mContentParent → mLayoutInflater.inflate(layoutResID, mContentParent) 把我们的 XML 挂进系统布局。至此,应用自己的 layout 与系统视图层次正式接轨。后半段涉及 LayoutInflater 如何解析 XML、把标签逐个变成 View 对象并组装成树,留待下篇分析。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved