閱讀setContentView()源碼的疑問
首先讀源碼要帶著自己的疑問來讀源碼寞埠,setContentView()到底做了什么,為什么調(diào)用后就可以顯示出我們想要的布局頁面新翎?getWindow().requestFeature(Window.FEATURE_NO_TITLE);為什么要在setContentView()之前調(diào)用,下面我就就帶著這些疑問來一探究竟。
/**
* 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();
}
進(jìn)入到setContentView()额嘿,我們發(fā)現(xiàn)調(diào)用的是getWindow()的setContentView()方法,getWindow()其實就是一個Window劣挫,Window是一個抽象類册养,從注釋我們可以知道Window的唯一實現(xiàn)類是PhoneWindow。
/**
* Abstract base class for a top-level window look and behavior policy. An
* instance of this class should be used as the top-level view added to the
* window manager. It provides standard UI policies such as a background, title
* area, default key processing, etc.
*
* <p>The only existing implementation of this abstract class is
* android.view.PhoneWindow, which you should instantiate when needing a
* Window.
*/
public abstract class Window
也就是說Activity的setContentView()調(diào)用的是PhoneWindow的setContentView(),我們再看下PhoneWindow的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(); //1
} 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); //2
}
...
}
在這里會對mContentParent進(jìn)行判空压固,mContentParent是一個ViewGroup球拦,從名字和代碼②mLayoutInflater.inflate(layoutResID, mContentParent); 我們可以先猜測一下Activity要顯示的布局是不是就加載到mContentParent中呢?我們先留個疑問帐我,稍后分析inflate()坎炼。
// 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.
ViewGroup mContentParent;
注釋:這是放置窗口內(nèi)容的視圖。 它是mDecor本身拦键,或mDecor的一個孩子谣光。
當(dāng)mContentParent為null時,就會執(zhí)行代碼① installDecor();我們再進(jìn)入到 installDecor()矿咕。
private void installDecor() {
mForceDecorInstall = false;
if (mDecor == null) {
mDecor = generateDecor(-1);
mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
mDecor.setIsRootNamespace(true);
if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
}
} else {
mDecor.setWindow(this);
}
if (mContentParent == null) {
mContentParent = generateLayout(mDecor); //*********3**********
...
}
}
}
當(dāng)我們新啟動一個Activity是mDecor 和 mContentParent 都是為空的抢肛,分別看下generateDecor()和generateLayout(mDecor)都做了什么。
創(chuàng)建generateDecor
protected DecorView generateDecor(int featureId) {
// System process doesn't have application context and in that case we need to directly use
// the context we have. Otherwise we want the application context, so we don't cling to the
// activity.
Context context;
if (mUseDecorContext) {
Context applicationContext = getContext().getApplicationContext();
if (applicationContext == null) {
context = getContext();
} else {
context = new DecorContext(applicationContext, getContext().getResources());
if (mTheme != -1) {
context.setTheme(mTheme);
}
}
} else {
context = getContext();
}
return new DecorView(context, featureId, this, getAttributes());
}
這里就是創(chuàng)建一個DecorView碳柱,DecorView又是什么呢捡絮?DecorView繼承于FrameLayout,在代碼3處將創(chuàng)建的這個DecorView作為參數(shù)傳到了generateLayout()中莲镣。
創(chuàng)建generateLayout
protected ViewGroup generateLayout(DecorView decor) {
// Apply data from current theme.
//獲得style屬性
TypedArray a = getWindowStyle();
...
...
if (a.getBoolean(R.styleable.Window_windowNoTitle, false)) {
requestFeature(FEATURE_NO_TITLE);
} else if (a.getBoolean(R.styleable.Window_windowActionBar, false)) {
// Don't allow an action bar if there is no title.
requestFeature(FEATURE_ACTION_BAR);
}
if (a.getBoolean(R.styleable.Window_windowActionBarOverlay, false)) {
requestFeature(FEATURE_ACTION_BAR_OVERLAY);
}
if (a.getBoolean(R.styleable.Window_windowActionModeOverlay, false)) {
requestFeature(FEATURE_ACTION_MODE_OVERLAY);
}
if (a.getBoolean(R.styleable.Window_windowSwipeToDismiss, false)) {
requestFeature(FEATURE_SWIPE_TO_DISMISS);
}
...
// Inflate the window decor.
int layoutResource;
int features = getLocalFeatures();
if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
layoutResource = R.layout.screen_swipe_dismiss;
} else if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
layoutResource = R.layout.screen_title_icons;
} else {
// Embedded, so no decoration is needed.
layoutResource = R.layout.screen_simple;
// System.out.println("Simple!");
}
...
mDecor.startChanging();
mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT)福稳; //*****4*****
if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
ProgressBar progress = getCircularProgressBar(false);
if (progress != null) {
progress.setIndeterminate(true);
}
}
if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
registerSwipeCallbacks();
}
return contentParent;
}
我們可以看到首先獲得style屬性,判斷是否有WindowNoTitle等等一些屬性瑞侮,然后調(diào)用一大堆requestFeature()和setFlags(),就是對Window一些狀態(tài)屬性的設(shè)置的圆,mContentParentExplicitlySet是一個標(biāo)記鼓拧,在調(diào)用setContentView()中就會設(shè)置為true,這就解開了文章開頭的疑問,為什么要在setContentView()之前設(shè)置requestFeature(Window.FEATURE_NO_TITLE);
@Override
public boolean requestFeature(int featureId) {
if (mContentParentExplicitlySet) {
throw new AndroidRuntimeException("requestFeature() must be called before adding content");
}
上面其中還有一段代碼 int features = getLocalFeatures()越妈,來獲得對Window所設(shè)置的features 季俩,系統(tǒng)會根據(jù)features 來加載不同的XML文件,這個文件就是將要加載到window decor里面的,再次說明requestFeature()要在setContentView()之前設(shè)置梅掠,我們來看一下加載的其中一個XML文件R.layout.screen_simple酌住,
R.layout.screen_simple
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<ViewStub android:id="@+id/action_mode_bar_stub"
android:inflatedId="@+id/action_mode_bar"
android:layout="@layout/action_mode_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="?attr/actionBarTheme" />
<FrameLayout
android:id="@android:id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foregroundInsidePadding="false"
android:foregroundGravity="fill_horizontal|top"
android:foreground="?android:attr/windowContentOverlay" />
</LinearLayout>
這就是DecorView加載的布局,注意FrameLayout的id阎抒,通過代碼④找到這個id為ID_ANDROID_CONTENT的ViewGroup酪我,可以發(fā)現(xiàn)ID_ANDROID_CONTENT就是FrameLayout。
/**
* The ID that the main layout in the XML layout file should have.
*/
public static final int ID_ANDROID_CONTENT = com.android.internal.R.id.content;
最后又返回contentParent且叁,也就是說mContentParent 就是這個id為content的FrameLayout都哭。我們看下面的視圖
我們總結(jié)一下圖片,每一個Activity對應(yīng)一個Window,PhoneWindow是Window的子類逞带,DecorView是PhoneWindow的內(nèi)部類欺矫,加載Activity顯示的視圖,現(xiàn)在對窗口的視圖有了清晰的了解展氓。
LayoutInflater 把xml添加到Decorview分析
1.include 為什么不能xml資源布局的根節(jié)點汇陆?
2.merge 為什么作為xml資源布局的根節(jié)點?
我們來看下setContentView()中mLayoutInflater.inflate(layoutResID, mContentParent)的部分带饱,LayoutInflater的inflater(layoutResID毡代,mContentParent)方法
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
/**
* Inflate a new view hierarchy from the specified XML node. Throws
* {@link InflateException} if there is an error.
* <p>
* <em><strong>Important</strong></em> For performance
* reasons, view inflation relies heavily on pre-processing of XML files
* that is done at build time. Therefore, it is not currently possible to
* use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
*
* @param parser XML dom node containing the description of the view
* hierarchy.
* @param root Optional view to be the parent of the generated hierarchy (if
* <em>attachToRoot</em> is true), or else simply an object that
* provides a set of LayoutParams values for root of the returned
* hierarchy (if <em>attachToRoot</em> is false.)
* @param attachToRoot Whether the inflated hierarchy should be attached to
* the root parameter? If false, root is only used to create the
* correct subclass of LayoutParams for the root view in the XML.
* @return The root View of the inflated hierarchy. If root was supplied and
* attachToRoot is true, this is root; otherwise it is the root of
* the inflated XML file.
*/
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser); //獲得的是Activity顯示布局的屬性
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
View result = root; //將DecorView布局中的FrameLayout賦值給result
...
// Look for the root node. //找到根節(jié)點
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (TAG_MERGE.equals(name)) {
if (root == null || !attachToRoot) {
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
rInflate(parser, root, inflaterContext, attrs, false);
} else {
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
// Create layout params that match root, if supplied //創(chuàng)建與root匹配的布局參數(shù)(如果提供)
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
// Inflate all children under temp against its context. //填充temp下面的子View
rInflateChildren(parser, temp, attrs, true);
...
}
...
return result;
}
}
上面三段代碼依次調(diào)用,如果是meger標(biāo)簽時調(diào)用 rInflate(parser, root, inflaterContext, attrs, false);如果不是meger標(biāo)簽時會調(diào)用View temp = createViewFromTag(root, name, inflaterContext, attrs); 上面有一句注釋// Temp is the root view that was found in the xml勺疼,意思是:Temp是在xml中找到的根視圖教寂,也就是我們Activity顯示布局的根視圖,然后調(diào)用root.generateLayoutParams(attrs);來解析根布局的參數(shù)并進(jìn)行設(shè)置执庐, 下面我們看下rInflateChildren(parser, temp, attrs, true)
/**
* Recursive method used to inflate internal (non-root) children. This
* method calls through to {@link #rInflate} using the parent context as
* the inflation context.
* <strong>Note:</strong> Default visibility so the BridgeInflater can
* call it.
*/
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
boolean finishInflate) throws XmlPullParserException, IOException {
rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}
我們發(fā)現(xiàn)最后都是調(diào)用rInflate()只是最后一個參數(shù)finishInflate不同酪耕,meger傳false,反之轨淌。
/**
* Recursive method used to descend down the xml hierarchy and instantiate
* views, instantiate their children, and then call onFinishInflate().
* <p>
* <strong>Note:</strong> Default visibility so the BridgeInflater can
* override it.
*/
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
final int depth = parser.getDepth();
int type;
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
final String name = parser.getName();
if (TAG_REQUEST_FOCUS.equals(name)) {
parseRequestFocus(parser, parent);
} else if (TAG_TAG.equals(name)) {
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
![LayoutInflater.png](http://upload-images.jianshu.io/upload_images/4029647-7d295d44aaf5b9aa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
throw new InflateException("<merge /> must be the root element");
} else {
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflateChildren(parser, view, attrs, true);
viewGroup.addView(view, params);
}
}
if (finishInflate) {
parent.onFinishInflate();
}
}
我們發(fā)現(xiàn)是一個while循環(huán)迂烁,也就是通過遍歷去解析的,看下解析過程會判斷節(jié)點的名稱递鹉,其中判斷到TAG_INCLUDE和TAG_MERGE標(biāo)簽時我們會看到拋出兩個異常盟步,這就解釋了開始提出的兩個問題。最后else還是重復(fù)了rInflateChildren(),然后添加到viewGroup里面躏结,這個過程用下面圖片說明一下解析XML 的大致過程却盘。
現(xiàn)在我們用AS開發(fā)默認(rèn)都是繼承AppCompatActivity,那么AppCompatActivity的setContentView()也是這樣呢!黄橘!答案肯定不是的兆览,我們下篇分析!
(第一篇源碼分析文章塞关,希望讀者給出建議L健)