View 繪制體系知識梳理(2) - setContentView 源碼解析

一、概述

Activity當中,我們一般都會調用setContentView方法來初始化布局。

二、與ContentView相關的方法

Activity當中,與ContentView相關的函數有下面這幾個,我們先看一下它們的注釋說明:

    /**
     * Set the activity content from a layout resource.  The resource will be
     * inflated, adding all top-level views to the activity.
     *
     * @param layoutResID Resource ID to be inflated.
     *
     * @see #setContentView(android.view.View)
     * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
     */
    public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }

    /**
     * Set the activity content to an explicit view.  This view is placed
     * directly into the activity's view hierarchy.  It can itself be a complex
     * view hierarchy.  When calling this method, the layout parameters of the
     * specified view are ignored.  Both the width and the height of the view are
     * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use
     * your own layout parameters, invoke
     * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
     * instead.
     *
     * @param view The desired content to display.
     *
     * @see #setContentView(int)
     * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
     */
    public void setContentView(View view) {
        getWindow().setContentView(view);
        initWindowDecorActionBar();
    }

    /**
     * Set the activity content to an explicit view.  This view is placed
     * directly into the activity's view hierarchy.  It can itself be a complex
     * view hierarchy.
     *
     * @param view The desired content to display.
     * @param params Layout parameters for the view.
     *
     * @see #setContentView(android.view.View)
     * @see #setContentView(int)
     */
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        getWindow().setContentView(view, params);
        initWindowDecorActionBar();
    }

    /**
     * Add an additional content view to the activity.  Added after any existing
     * ones in the activity -- existing views are NOT removed.
     *
     * @param view The desired content to display.
     * @param params Layout parameters for the view.
     */
    public void addContentView(View view, ViewGroup.LayoutParams params) {
        getWindow().addContentView(view, params);
        initWindowDecorActionBar();
    }

通過上面的注釋,可以看到這4個方法的用途:

  • 第一種:渲染layouResId對應的布局,并將它添加到activity的頂級View中。
  • 第二種:將View添加到activity的布局當中,它的默認寬高都是ViewGroup.LayoutParams#MATCH_PARENT
  • 第三種:和上面相同,但是指定了LayoutParams
  • 第四種:將內容添加進去,并且必須指定LayoutParams,已經存在的View不會被移除。

這四種方法其實都是調用了PhoneWindow.java中的方法,通過源碼我們可以發(fā)現setContentView(View view, ViewGroup.LayoutParams params)setContentView(@LayoutRes int layoutResID)的步驟基本上是一樣的,只不過是在添加到布局的時候,前者因為已經獲得了View的實例,因此用的是addView的方法,而后者因為需要先inflate,所以,使用的是LayoutInflater

三、setContentView方法

下面我們以setContentView(@LayoutRes int layoutResID)為例,看一下具體的實現步驟:

3.1 setContentView

    @Override
    public void setContentView(int layoutResID) {
        // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
        // decor, when theme attributes and the like are crystalized. Do not check the feature
        // before this happens.
        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();
        }
        mContentParentExplicitlySet = true;
    }

首先,我們會判斷mContentParent是否為空,通過添加的代碼我們可以知道,這個mContentParent其實就是layoutResId最后渲染出的布局所對應的父容器,當這個ContentParent為空時,調用了installDecormContentParent就是在里面初始化的。

3.2 installDecor()

    private void installDecor() {
        //如果DecorView不存在,那么先生成它,它其實是一個FrameLayout。
        if (mDecor == null) {
            mDecor = generateDecor();
        }
        //如果`ContentParent`不存在,那么也生成它,此時傳入了前面的`DecorView`
        if (mContentParent == null) {
            mContentParent = generateLayout(mDecor);
            final DecorContentParent decorContentParent = (DecorContentParent) mDecor.findViewById(R.id.decor_content_parent);
            if (decorContentParent != null) {
                mDecorContentParent = decorContentParent;
            }
        }
    }

我們可以看到,mDecor是一個FrameLayout,它和mContentParent的關系是通過mContentParent = generateLayout(mDecor)產生。

3.3 generateLayout(DecorView decor)

    protected ViewGroup generateLayout(DecorView decor) {
        //...首先根據不同的情況,給`layoutResource`賦予不同的值.
        View in = mLayoutInflater.inflate(layoutResource, null);
        decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
        mContentRoot = (ViewGroup) in;
        ViewGroup contentParent = (ViewGroup) findViewById(ID_ANDROID_CONTENT);
        if (contentParent == null) {
            throw new RuntimeException("Window couldn't find content container view");
        }
        //...
        return contentParent;
    }

在上面賦值的過程中,我們主要關注以下幾個變量,mContentRoot/mContentParent/mDecorContent

  • mContentRoot一定是mDecor的下一級子容器。
  • mContentParentmDecor當中idR.id.contentViewGroup,但是它mDecor的具體層級關系不確定,這依賴于mContentRoot是通過哪個xml渲染出來。
  • mContentParent一定是傳入的layoutResId進行 inflate完成之后的父容器,它一定不會為空,否則會拋出異常,我們setContentView(xxx)方法傳入的布局,就是它的子View
    // This is the top-level view of the window, containing the window decor.
    private DecorView mDecor;

    // 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.
    private ViewGroup mContentParent;
  • mDecorContent則是mDecor當中iddecor_content_parentViewGroup,但是也有可能mDecor
    當中沒有這個idView,這需要依賴與我們的mContentRoot是使用了哪個xmlinflate的。

再回到前面setContentView的地方,繼續(xù)往下看,mContentParent不為空的時候,那么會移除它底下的所有子View
之后會調用mLayoutInflater.inflate(layoutResID, mContentParent);方法,把傳入的View添加到mContentParent當中,最后回調一個監(jiān)聽。

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

3.4 mContentParentExplicitlySet標志位

setContentView的最后,將mContentParentExplicitlySet這個變量設置為true,這個變量其實是用在requestFeature當中,也就是說,我們必須在調用setContentView之前,調用requestFeature,否則就會拋出下面的異常:

    @Override
    public boolean requestFeature(int featureId) {
        if (mContentParentExplicitlySet) {
            throw new AndroidRuntimeException("requestFeature() must be called before adding content");
        }
        return super.requestFeature(featureId);
    }

因此:requestFeature(xxx)必須要在調用setContentView(xxx)之前

三、addContentView(View view, ViewGroup.LayoutParams params)

下面我們再來看一下,addContentView方法:

    @Override
    public void addContentView(View view, ViewGroup.LayoutParams params) {
        if (mContentParent == null) {
            installDecor();
        }
        mContentParent.addView(view, params);
        mContentParent.requestApplyInsets();
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
    }

可以看到,它和set方法的區(qū)別就是,它在添加到mContentParent之前,并沒有把mContentParent的所有子View都移除,而是將它直接添加進去,通過布局分析軟件,可以看到mContentParent的類型為ContentFrameLayout,它其實是一個FrameLayout,因此,它會覆蓋在mContentParent已有子View之上

四、將添加的布局和ActivityWindow關聯(lián)起來

在上面的分析當中,我們僅僅是初始化了一個DecorView,并根據設置的Style屬性,傳入的ContentView來初始化它的子布局,但是這時候它還有真正和ActivityWindow關聯(lián)起來,關聯(lián)的地方在ActivityThread.java中:

final void handleResumeActivity(IBinder token,
            boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
        r = performResumeActivity(token, clearHide, reason);
        if (r != null) {
            if (r.window == null && !a.mFinished && willBeVisible) {
                r.window = r.activity.getWindow();
                View decor = r.window.getDecorView();
                decor.setVisibility(View.INVISIBLE);
                ViewManager wm = a.getWindowManager();
                WindowManager.LayoutParams l = r.window.getAttributes();
                a.mDecor = decor;
                l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
                l.softInputMode |= forwardBit;
                if (r.mPreserveWindow) {
                    a.mWindowAdded = true;
                    r.mPreserveWindow = false;
                    // Normally the ViewRoot sets up callbacks with the Activity
                    // in addView->ViewRootImpl#setView. If we are instead reusing
                    // the decor view we have to notify the view root that the
                    // callbacks may have changed.
                    ViewRootImpl impl = decor.getViewRootImpl();
                    if (impl != null) {
                        impl.notifyChildRebuilt();
                    }
                }
                if (a.mVisibleFromClient && !a.mWindowAdded) {
                    a.mWindowAdded = true;
                    wm.addView(decor, l);
                }
            } else if (!willBeVisible) {
                if (localLOGV) Slog.v(
                    TAG, "Launch " + r + " mStartedActivity set");
                r.hideForNow = true;
            }
        } else {

        }
    }

從源碼中可以看到,如果在執(zhí)行handleResumeActivity時,之前DecorView沒有被添加到WindowManager當中時,那么它的第一次添加是在onResume()方法執(zhí)行完之后添加的

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,732評論 6 539
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現死者居然都...
    沈念sama閱讀 99,214評論 3 426
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,781評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,588評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,315評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,699評論 1 327
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,698評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,882評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體,經...
    沈念sama閱讀 49,441評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,189評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,388評論 1 372
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,933評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,613評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,023評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,310評論 1 293
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,112評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,334評論 2 377

推薦閱讀更多精彩內容