一、概述
在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
為空時,調用了installDecor
,mContentParent
就是在里面初始化的。
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
的下一級子容器。 -
mContentParent
是mDecor
當中id
為R.id.content
的ViewGroup
,但是它和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
當中id
為decor_content_parent
的ViewGroup
,但是也有可能mDecor
當中沒有這個id
的View
,這需要依賴與我們的mContentRoot
是使用了哪個xml
來inflate
的。
再回到前面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
之上。
四、將添加的布局和Activity
的Window
關聯(lián)起來
在上面的分析當中,我們僅僅是初始化了一個DecorView
,并根據設置的Style
屬性,傳入的ContentView
來初始化它的子布局,但是這時候它還有真正和Activity
的Window
關聯(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í)行完之后添加的。