前言
看源碼是一個枯燥的過程亲族,為了達到效果霎迫,我們需要帶著問題帘靡,有目的地去看源碼
問題
我們經(jīng)常使用的Activity的
onCreate
方法里setContentView(R.layout.activity_main)
是如何加載我們的布局文件的?
源碼分析
- 找到
Activity
類的setContentView
方法:
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
第一行代碼調(diào)用了getWindow()
方法來獲取Window
類的對象涩赢,然后調(diào)用了Window
類的setContentView
方法
- 我們找到
Window
類:
/**
* 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 {
/** Flag for the "options panel" feature. This is enabled by default. */
public static final int FEATURE_OPTIONS_PANEL = 0;
...
...
...
public abstract void setContentView(@LayoutRes int layoutResID);
...
...
...
}
這里Window
是個抽象類轩勘,而我們從注釋The only existing implementation of this abstract class is android.view.PhoneWindow
唯一的實現(xiàn)類是PhoneWindow
绊寻,也就是實際調(diào)用的是PhoneWindow
- 我們找到
PhoneWindow
類的setContentView
方法:
public void setContentView(int layoutResID) {
...
...
...
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
transitionTo(newScene);
} else {
mLayoutInflater.inflate(layoutResID, mContentParent);
}
...
...
...
}
這里我們就只分析核心代碼了,其他的先不看冰蘑,這里可以看到如果沒有轉(zhuǎn)場動畫村缸,就調(diào)用mLayoutInflater.inflate(layoutResID, mContentParent)
,我們這里先把傳入的mContentParent
看作是一個布局父控件
- 轉(zhuǎn)到
LayoutInflater
的inflate(int resource,ViewGroup root)
方法:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
這里調(diào)用了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();
}
}
看到XmlResourceParser
應(yīng)該不會感到陌生了吧搪柑,接下來看調(diào)用inflate(parser, root, attachToRoot)
如何解析xml布局文件
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
...
...
...
View result = root;
try {
// Look for the root node.
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
final String name = parser.getName();
if (DEBUG) {
System.out.println("**************************");
System.out.println("Creating root view: "
+ name);
System.out.println("**************************");
}
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) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// Create layout params that match root, if supplied
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);
}
}
if (DEBUG) {
System.out.println("-----> start inflating children");
}
// Inflate all children under temp against its context.
rInflateChildren(parser, temp, attrs, true);
if (DEBUG) {
System.out.println("-----> done inflating children");
}
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// Decide whether to return the root that was passed in or the
// top view found in xml.
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
InflateException ex = new InflateException(e.getMessage());
ex.initCause(e);
throw ex;
} catch (Exception e) {
InflateException ex = new InflateException(
parser.getPositionDescription()
+ ": " + e.getMessage());
ex.initCause(e);
throw ex;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
}
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
return result;
}
}
這段代碼xml解析百姓,如果解析到merge
標(biāo)簽况木,就調(diào)用rInflate(parser, root, inflaterContext, attrs, false)
,如果不是則先createViewFromTag(root, name, inflaterContext, attrs)
創(chuàng)建一個view
火惊,然后調(diào)用root.generateLayoutParams(attrs)
來生成LayoutParams
,然后遞歸調(diào)用rInflateChildren(parser, temp, attrs, true)
遍歷所有的標(biāo)簽完成解析尸疆,最后root.addView(temp, params)
完成界面加載.
最后附上一張布局文件解析流程圖