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

澤毛發表於2017-12-21

一、概述

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中的方法,通過原始碼我們可以發現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的地方,繼續往下看,mContentParent不為空的時候,那麼會移除它底下的所有子View。 之後會呼叫mLayoutInflater.inflate(layoutResID, mContentParent);方法,把傳入的View新增到mContentParent當中,最後回撥一個監聽。

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方法的區別就是,它在新增到mContentParent之前,並沒有把mContentParent的所有子View都移除,而是將它直接新增進去,通過佈局分析軟體,可以看到mContentParent的型別為ContentFrameLayout,它其實是一個FrameLayout,因此,它會覆蓋在mContentParent已有子View之上

四、將新增的佈局和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()方法執行完之後新增的

相關文章