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

Android View 系統剖析(一):從 setContentView 說起

編輯:關於 Android 程式設計

從 Hello World 談起

學習任何語言或平台,第一個專案大概都逃不掉 Hello World,這個傳統自 K&R 開了先例之後就很少有人打破。Android 也不例外:建立專案、跑起來、在模擬器上看到一行字。最精簡的 Activity 大致長這樣:

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
    }
}

對應的配置檔:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
</RelativeLayout>

執行後畫面上出現了 Hello World。但仔細看會發現一件有意思的事:我們的配置檔裡只有一個 TextView,畫面上卻還多了一個標題欄。這個標題欄是誰畫上去的?整個過程究竟如何運作?大型系統的細節總是繁雜,這篇只把基本脈絡理清楚。

setContentView 做了什麼

以 2.3 的原始碼為例:

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

public Window getWindow() {
    return mWindow;
}

private Window mWindow;

可以看到,實際工作被轉交給了 mWindow。而 Window 的實作類別是 PhoneWindow,於是繼續往下追:

@Override
public void setContentView(int layoutResID) {
    if (mContentParent == null) {
        installDecor(); // 1、生成 DecorView
    } else {
        mContentParent.removeAllViews();
    }
    mLayoutInflater.inflate(layoutResID, mContentParent); // 2、把配置內容塞進 mContentParent
    final Callback cb = getCallback();
    if (cb != null) {
        cb.onContentChanged();
    }
}

// 建立 mDecor,並初始化標題欄與內容顯示區
private void installDecor() {
    if (mDecor == null) {
        mDecor = generateDecor(); // 3、建立 DecorView
        mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
        mDecor.setIsRootNamespace(true);
    }
    if (mContentParent == null) {
        mContentParent = generateLayout(mDecor); // 4、取得內容容器
        mTitleView = (TextView) findViewById(com.android.internal.R.id.title);
        // 5、處理 Title
        if (mTitleView != null) {
            if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) {
                View titleContainer = findViewById(com.android.internal.R.id.title_container);
                if (titleContainer != null) {
                    titleContainer.setVisibility(View.GONE);
                } else {
                    mTitleView.setVisibility(View.GONE);
                }
                if (mContentParent instanceof FrameLayout) {
                    ((FrameLayout) mContentParent).setForeground(null);
                }
            } else {
                mTitleView.setText(mTitle);
            }
        }
    }
}

protected DecorView generateDecor() {
    return new DecorView(getContext(), -1);
}

歸納起來,setContentView 的流程就是:建立 mDecor(整個視窗的頂層視圖,內含 Title 與 Content 兩個區域)、初始化這兩個區域、最後把我們寫的 XML 內容膨脹後附加到 Content 區域。其中比較複雜的是 generateLayout()。

generateLayout:決定長什麼樣

這個方法做的事可以拆成幾塊。首先讀取主題套用後的視窗屬性(是否浮動、要不要標題、是否全螢幕、是否顯示桌布、輸入法模式、背景變暗、視窗動畫、背景與框線資源、文字顏色等),然後依 feature 決定要載入哪一種頂層版面配置:

int layoutResource;
int features = getLocalFeatures();
if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
    layoutResource = mIsFloating
        ? com.android.internal.R.layout.dialog_title_icons
        : com.android.internal.R.layout.screen_title_icons;
} else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0) {
    layoutResource = com.android.internal.R.layout.screen_progress;
} else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
    layoutResource = mIsFloating
        ? com.android.internal.R.layout.dialog_custom_title
        : com.android.internal.R.layout.screen_custom_title;
} else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
    layoutResource = mIsFloating
        ? com.android.internal.R.layout.dialog_title
        : com.android.internal.R.layout.screen_title;
} else {
    layoutResource = com.android.internal.R.layout.screen_simple;
}

mDecor.startChanging();
// 載入頂層版面配置
View in = mLayoutInflater.inflate(layoutResource, null);
// 掛到 mDecor 底下
decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
// 取出內容顯示區(FrameLayout)
ViewGroup contentParent = (ViewGroup) findViewById(ID_ANDROID_CONTENT);
if (contentParent == null) {
    throw new RuntimeException("Window couldn't find content container view");
}
// 設定背景、框線、標題等
if (getContainer() == null) {
    Drawable drawable = mBackgroundDrawable;
    if (mBackgroundResource != 0) {
        drawable = getContext().getResources().getDrawable(mBackgroundResource);
    }
    mDecor.setWindowBackground(drawable);
    drawable = null;
    if (mFrameResource != 0) {
        drawable = getContext().getResources().getDrawable(mFrameResource);
    }
    mDecor.setWindowFrame(drawable);
    if (mTitleColor == 0) {
        mTitleColor = mTextColor;
    }
    if (mTitle != null) {
        setTitle(mTitle);
    }
    setTitleColor(mTitleColor);
}
mDecor.finishChanging();
return contentParent;

我們挑一個最典型的情況來看,也就是 screen_title:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:fitsSystemWindows="true">
    <!-- Action mode 的浮出bar -->
    <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" >
        <TextView
            android:id="@android:id/title"
            android:background="@null"
            android:fadingEdge="horizontal"
            android:gravity="center_vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>
    <!-- 內容顯示區域,main_activity.xml 會被放進這個 ViewGroup -->
    <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>

結構一目了然:上面是標題區,下面是內容區。前面程式碼裡 findViewById(ID_ANDROID_CONTENT) 抓的,就是這個 id 為 content 的 FrameLayout。這兩個區域合起來構成 mDecor,而我們的 main_activity.xml 最終就是被放進內容區裡的。

所以 generateLayout 的職責是:讀屬性 → 依屬性挑選頂層版面 → 膨脹成 View 並掛進 mDecor → 取出內容容器 → 套用背景與標題樣式,最後把內容容器回傳。

回到 setContentView

有了 mContentParent 之後,剩下的事情就很直白:

public void setContentView(int layoutResID) {
    if (mContentParent == null) {
        installDecor(); // 建立 DecorView、載入頂層版面、取得 mContentParent、套用基本屬性
    } else {
        mContentParent.removeAllViews();
    }
    mLayoutInflater.inflate(layoutResID, mContentParent); // 把我們的配置附加進去
    final Callback cb = getCallback();
    if (cb != null) {
        cb.onContentChanged();
    }
}

而 inflate() 最終就是把 layoutResId 描述的視圖樹附加到 mContentParent:

public View inflate(int resource, ViewGroup root) {
    return inflate(resource, root, root != null);
}

public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
    XmlResourceParser parser = getContext().getResources().getLayout(resource);
    try {
        return inflate(parser, root, attachToRoot);
    } finally {
        parser.close();
    }
}

注意 attachToRoot 這個參數:root 不為 null 時它才為 true。這也解釋了為什麼在自訂 View 或 Fragment 裡 inflate 配置時,傳入的 root 若只是為了提供 LayoutParams,就該把 attachToRoot 明確設為 false,否則會出現重複附加的問題。

DecorView、ViewGroup 與 View

DecorView 是每個視窗的頂層容器,前面出現的標題區與內容區都掛在它底下。

ViewGroup 顧名思義就是視圖組,同樣繼承自 View,但角色是容器。官方定義說得很清楚:它是一種能容納其他子視圖(children)的特殊 View,是所有版面配置與容器類別的基底類別,並定義了 LayoutParams 作為版面參數的基礎類別。我們常見的 FrameLayout、LinearLayout、RelativeLayout、ListView 都屬於 ViewGroup——只要能裝別的 View 或 ViewGroup,它就是 ViewGroup。整棵視圖樹就是靠它組織起來的。

View 則是 UI 上任何可見元件的最小單位。官方描述:它代表使用者介面元件的基本建構單元,在螢幕上佔據一個矩形區域,負責繪製與事件處理;它是 widgets(按鈕、文字輸入等互動元件)的基底類別,而 ViewGroup 子類則是 layouts——那些不可見、負責排列其他 View 的容器。TextView、Button、ImageView、LinearLayout、ListView 全都是 View 的子類。

小結

整個視窗由 Title 區與 Content 區組成。Content 區裡,mContentParent 是根 ViewGroup,由它組織管理子視圖,逐層搭建出完整的視圖樹。Activity 啟動時,這棵樹被測量、配置、繪製,最終呈現在螢幕上。

理解這條脈絡之後,再去看 requestWindowFeature() 為什麼必須在 setContentView() 之前呼叫、或者 ActionBar 自訂、無標題視窗等需求該從哪裡下手,都會順暢很多——因為它們全都是在 installDecor()/generateLayout() 階段被決定的。

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