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

Activity 的界面是怎麼挂上窗口的:setContentView 源碼全流程追蹤

編輯:關於 Android 程式設計

上一篇談 Handler 原理時,說到 Activity 啟動如何走到 onCreate。本篇接著從 onCreate 裡必寫的 setContentView 出發,把佈局視圖最終呈現在手機窗口上的過程完整走一遍。

一、setContentView 只是個入口

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

實際工作交给了 Window:

private Window mWindow;

public Window getWindow() {
    return mWindow;
}

二、mWindow 到底是誰

Window 是抽象類,需要找到它的實現類。mWindow 在 attach 方法中生成:

final void attach(...) {
    ...
    mWindow = PolicyManager.makeNewWindow(this);
    mWindow.setCallback(this);
    mWindow.getLayoutInflater().setPrivateFactory(this);
    ...
}

attach 由 main 方法調用,這裡透過 PolicyManager 的靜態方法創建視窗:

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

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

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

Policy 實例是靠反射加載的,而它的 makeNewWindow 返回的正是 PhoneWindow:

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

依多型規則,前面那句 getWindow().setContentView() 實際調用的是 PhoneWindow#setContentView。

三、PhoneWindow 的 setContentView

public void setContentView(int layoutResID) {
    if (mContentParent == null) {
        installDecor();                       // 1. 建立裝飾視圖
    } else {
        mContentParent.removeAllViews();
    }
    // 2. 把我們的佈局 inflate 進 mContentParent
    mLayoutInflater.inflate(layoutResID, mContentParent);

    final Callback cb = getCallback();
    if (cb != null && !isDestroyed()) {
        cb.onContentChanged();
    }
}

installDecor 的職責是準備好那個叫 mContentParent 的容器:

private void installDecor() {
    if (mDecor == null) {
        mDecor = generateDecor();   // 裝飾視圖,繼承自 FrameLayout
        mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
        mDecor.setIsRootNamespace(true);
        ...
    }
    if (mContentParent == null) {
        mContentParent = generateLayout(mDecor);
        mDecor.makeOptionalFitsSystemWindows();
        mTitleView = (TextView) findViewById(com.android.internal.R.id.title);
        ...
    }
}

四、generateLayout:窗口風格從哪來

我們在 AndroidManifest 裡配置的各種窗口特性,其實都是在這裡被解析並轉成具體佈局的:

protected ViewGroup generateLayout(DecorView decor) {
    // 讀取當前主題
    TypedArray a = getWindowStyle();
    ...

    if (a.getBoolean(com.android.internal.R.styleable.Window_windowNoTitle, false)) {
        requestFeature(FEATURE_NO_TITLE);
    } else if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionBar, false)) {
        requestFeature(FEATURE_ACTION_BAR);
    }
    if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionBarOverlay, false)) {
        requestFeature(FEATURE_ACTION_BAR_OVERLAY);
    }
    ...

    // 依 feature 組合挑選對應的系統佈局
    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;
    } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
            && (features & (1 << FEATURE_ACTION_BAR)) == 0) {
        layoutResource = com.android.internal.R.layout.screen_progress;
    } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
        layoutResource = com.android.internal.R.layout.screen_custom_title;
        removeFeature(FEATURE_ACTION_BAR);
    } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
        if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
            layoutResource = (features & (1 << FEATURE_ACTION_BAR_OVERLAY)) != 0
                    ? com.android.internal.R.layout.screen_action_bar_overlay
                    : com.android.internal.R.layout.screen_action_bar;
        } else {
            layoutResource = com.android.internal.R.layout.screen_title;
        }
    } else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
        layoutResource = com.android.internal.R.layout.screen_simple_overlay_action_mode;
    } else {
        layoutResource = com.android.internal.R.layout.screen_simple;
    }

    mDecor.startChanging();
    // 把選定的系統佈局填充成 View,掛到最外層的裝飾視圖下
    View in = mLayoutInflater.inflate(layoutResource, null);
    decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));

    // @android:id/content 對應的就是這個 FrameLayout
    ViewGroup contentParent = (ViewGroup) findViewById(ID_ANDROID_CONTENT);
    ...
    mDecor.finishChanging();
    return contentParent;
}

五、系統佈局長什麼樣

上述佈局檔案位於 frameworks/base/core/res/res/layout 目錄下。

Screen-title.xml(帶標題的常見樣式)

<LinearLayout
    android:fitsSystemWindows="true"
    android:orientation="vertical"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <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:layout_width="match_parent"
        android:layout_height="?android:attr/windowTitleSize"
        style="?android:attr/windowTitleBackgroundStyle">

        <TextView
            android:id="@android:id/title"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@null"
            android:fadingEdge="horizontal"
            android:gravity="center_vertical" />
    </FrameLayout>

    <FrameLayout
        android:id="@android:id/content"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:foregroundGravity="fill_horizontal|top"
        android:foreground="?android:attr/windowContentOverlay" />

</LinearLayout>

最外層是線性佈局,內部含一個標題 FrameLayout 和一個內容 FrameLayout——這正是我們最熟悉的默認樣子。

Screen-simple.xml(全屏無標題)

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

    <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>

無論哪個版本,id 為 content 的 FrameLayout 一定存在,因為它正是用來裝載我們自己佈局的容器。

六、結論

1. Activity 呈現的界面其實由 PhoneWindow 管理,其中 DecorView 是最外層容器。
2. 上面那張結構圖值得反覆看,它把整個窗口層級講清楚了。
3. 「Activity 究竟是什麼」這個問題,讀完源碼後恐怕很難再用一句話回答——至少和入門時的認識完全不同了。
4. 遇到想不通的問題就去讀源碼,代碼是最好的老師。

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