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

1、概述

Activity當中,咱們通常都會調用setContentView方法來初始化佈局。java

2、與ContentView相關的方法

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

/**
     * 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個方法的用途:bash

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

這四種方法其實都是調用了PhoneWindow.java中的方法,經過源碼咱們能夠發現setContentView(View view, ViewGroup.LayoutParams params)setContentView(@LayoutRes int layoutResID)的步驟基本上是同樣的,只不過是在添加到佈局的時候,前者由於已經得到了View的實例,所以用的是addView的方法,然後者由於須要先inflate,因此,使用的是LayoutInflaterapp

3、setContentView方法

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

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

  • 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的地方,繼續往下看,mContentParent不爲空的時候,那麼會移除它底下的全部子View。 以後會調用mLayoutInflater.inflate(layoutResID, mContentParent);方法,把傳入的View添加到mContentParent當中,最後回調一個監聽。this

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

3.4 mContentParentExplicitlySet標誌位

setContentView的最後,將mContentParentExplicitlySet這個變量設置爲true,這個變量實際上是用在requestFeature當中,也就是說,咱們必須在調用setContentView以前,調用requestFeature,不然就會拋出下面的異常:spa

@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)以前

3、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方法的區別就是,它在添加到mContentParent以前,並無把mContentParent的全部子View都移除,而是將它直接添加進去,經過佈局分析軟件,能夠看到mContentParent的類型爲ContentFrameLayout,它實際上是一個FrameLayout,所以,它會覆蓋在mContentParent已有子View之上

4、將添加的佈局和ActivityWindow關聯起來

在上面的分析當中,咱們僅僅是初始化了一個DecorView,並根據設置的Style屬性,傳入的ContentView來初始化它的子佈局,可是這時候它還有真正和ActivityWindow關聯起來,關聯的地方在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 {

        }
    }
複製代碼

從源碼中能夠看到,若是在執行handleResumeActivity時,以前DecorView沒有被添加到WindowManager當中時,那麼它的第一次添加是在onResume()方法執行完以後添加的

相關文章
相關標籤/搜索