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

GUI 系統之 View 體系(二):setContentView 源碼剖析

編輯:關於 Android 開發

本文從 Activity 的 setContentView 方法講起,逐層剖析 Android GUI 系統中 View 體系的構建過程。

1. 從 setContentView 講起

1.1 Activity 的 setContentView 內容

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

首先要問:這個 getWindow 是什麼?其實它就是 mWindow,在 attach 方法裡定義:

mWindow = new PhoneWindow(this);

預設就是 PhoneWindow,也就是 Activity 裡包含的 window 實例。

接著看 PhoneWindow 的 setContentView:

@Override public void setContentView(int layoutResID) {
    if (mContentParent == null) {
        installDecor();
    } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
        mContentParent.removeAllViews();
    }
    if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
        final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID, getContext());
        transitionTo(newScene);
    } else {
        mLayoutInflater.inflate(layoutResID, mContentParent);
    }
    mContentParent.requestApplyInsets();
    final Callback cb = getCallback();
    if (cb != null && !isDestroyed()) {
        cb.onContentChanged();
    }
}

那 mContentParent 是什麼?看它的定義:

// This is the view in which the window contents are placed. It is either
// mDecor itself, or a child of mDecor where the contents go.

按註釋的意思,mContentParent 就是我們加入 layout 的父布局,它有兩種可能:DecorView 本身,或它的子 View。

1.2 installDecor

installDecor 主要做兩件事:第一,若需要則建立 Decor;第二,建立 mContentParent:

mContentParent = generateLayout(mDecor);

來看 generateLayout。它有大量判斷,但最終把 layout 加入 Decor 的過程其實就兩句:

View in = mLayoutInflater.inflate(layoutResource, null);
decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));

第一句把 layout id 變換成 View,第二句把 View 加入到 Decor 中。

1.3 把 Decor 加入到 Activity 中

Activity 中的 view,是透過 Window 然後跟 WMS(WindowManagerService)來管理的。一個 Activity 對象持有 mWindow 對象,其管理路徑如下:

mWindow -> WindowManager -> WindowManagerImpl -> WMS -> ViewRoot -> addView。

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