先上個(gè)圖:
上圖是LayoutInflate.inflate(...)的每個(gè)重載的方法中參數(shù)的類(lèi)型茄菊,方法也不是很多缘眶,我們就一個(gè)個(gè)來(lái)看看他源碼是怎么樣子的翰舌。
那么我們先把這幾個(gè)參數(shù)是做什么用的解釋了,以便后面方法的理解:
- int resource:布局文件xml的資源id
- ViewGroup root:如果attchToRoot為true的話唤锉,root作為父布局
- XmlPullParser parser:Android自帶的xml解析類(lèi)型世囊,產(chǎn)生DOM節(jié)點(diǎn)
- boolean attachToRoot:是否加載到root布局中
源碼分析:
可以從紅色框框看到調(diào)用的是第一張圖片中第三個(gè)重載方法:
那么我們?nèi)タ纯茨莻€(gè)調(diào)用的方法又是如何實(shí)現(xiàn)的:
從上圖代碼中,我么可以看到腌紧,其將傳入的xml布局解析成XmlResourceParser格式后茸习,調(diào)用了第一張圖片的第四個(gè)重載方法。在這里壁肋,根據(jù)第一個(gè)方法的return号胚,我們可以推測(cè)下,第二個(gè)方法是不是也是調(diào)用了第四個(gè)重載方法呢浸遗?現(xiàn)在就看源碼驗(yàn)證猫胁!
果然驗(yàn)證了我們的猜想,那么我們就來(lái)看看第四個(gè)重載方法跛锌,看看他的奧秘在哪里弃秆,先上源碼:
/**
* 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);
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
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;
}
}
可知道届惋,當(dāng)根節(jié)點(diǎn)是merge的時(shí)候,只能是在root != null && attachToRoot = true的時(shí)候菠赚,否者會(huì)報(bào)異常脑豹。
紅色框中,返回的是xml布局的LayoutParams參數(shù)大小衡查。該方法是調(diào)用ViewGroup中方法來(lái)實(shí)例化獲得LayoutParams數(shù)據(jù)瘩欺。所以就是說(shuō),當(dāng)沒(méi)有傳遞root進(jìn)來(lái)的時(shí)候拌牲。就不能獲得xml布局中的大小參數(shù)俱饿。而接著當(dāng)attachToRoot為false的時(shí)候,將params賦給temp塌忽。
從上面代碼我們知道拍埠,當(dāng) root != null && attachToRoot為true的時(shí)候,將temp添加到root布局中返回(這里return的是result土居,但在方法的一開(kāi)始有將root賦給result枣购,這里root與result其實(shí)就是等價(jià)的了)。而當(dāng)root == null || attachToRoot為false的時(shí)候擦耀,將temp賦給result返回坷虑。說(shuō)明,當(dāng)root == null 的時(shí)候埂奈,attachToRoot設(shè)置true/false都是沒(méi)關(guān)系的。
對(duì)了定躏。連注釋都忘了解釋?zhuān)?/p>
最后總結(jié):
- 若root = null账磺,則attachToRoot無(wú)所謂true/false,并不能獲得任何效果痊远,那么xml中最外層的布局的layout_width和layout_height設(shè)置將失效垮抗。
- 若root != null && attachToRoot = false,不加載到root中碧聪,使得Layout文件中(最常用的例子就是adapter中的layout)最外層的布局的layout_width和layout_height設(shè)置將有效冒版。
- 若root != null && attachToRoot = true,加載到root中逞姿,并將root返回辞嗡。
以上是個(gè)人學(xué)習(xí)觀點(diǎn),若有不恰當(dāng)或不正確的地方滞造,歡迎指正续室。一起學(xué)習(xí)。
hierarchy n. 層級(jí)谒养;等級(jí)制度