LayoutInflater 實(shí)例化獲取方法
1、一般我們獲取 LayoutInflater 對(duì)象都是通過(guò) LayoutInflater 的 from 方法
public static LayoutInflater from(Context context) {
LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null) {
throw new AssertionError("LayoutInflater not found.");
}
return LayoutInflater;
}
內(nèi)部封裝了 getSystemService 方法,
2挑格、我們也可以直接通過(guò)
LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
來(lái)獲取
3衷畦、Activity 也提供了 getLayoutInflater 方法阵谚,內(nèi)部是調(diào)用的 Window 類的 getLayoutInflater 方法鸟蟹,歸根到底還是通過(guò) getSystemService 來(lái)獲取泣洞。
LayoutInflater 的 View inflate(…) 方法族剖析
得到 LayoutInflater 對(duì)象之后我們就是傳遞 xml 然后解析得到 View
inflate 的重載方法有四個(gè):
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root)
public View inflate(XmlPullParser parser, @Nullable ViewGroup root)
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
根據(jù)第一個(gè)參數(shù)的區(qū)別全庸,上面四個(gè)方法可以分為兩組秀仲,第一組傳入的參數(shù)是 int 類型的資源文件 ID,第二組傳入的是一個(gè)XmlPullParser 對(duì)象壶笼,而其實(shí)傳入布局 ID 后神僵,也是被解析成了 XmlPullParser 對(duì)象,然后調(diào)用參數(shù)為 XmlPullParser 的重載方法:
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();
}
}
因?yàn)?layout 文件也是資源文件的一種覆劈,所以可以用Resources 的 getLayout 方法獲取保礼,返回的就是 XmlpullParser 對(duì)象沛励。
兩個(gè)參數(shù)的方法內(nèi)部會(huì)調(diào)用三個(gè)參數(shù)的方法:
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;
}
前面部分是從 XmlPullParser 中解析屬性,然后判斷布局文件的根標(biāo)簽是不是 merge炮障,如果是 merge 的話目派,第二個(gè)參數(shù)不能為 null,并且第三個(gè)參數(shù)必須為 true胁赢。因?yàn)?merge 只能作為 xml 文件的根元素企蹭,在 View 樹(shù)中必須加載在其它 ViewGroup 里。
接下來(lái)判斷第二個(gè)參數(shù) root 是否為 null智末,如果 root 不為 null谅摄,根據(jù)從 xml 文件中解析出來(lái)的 AttributeSet 中的 layout_width 和 layout_height 屬性生成 LayoutParams,如果第三個(gè)參數(shù) attachToRoot 為 true吹害,那么把解析出來(lái)的 View 根據(jù)生成的 LayoutParams 添加到 root 上螟凭,最后返回 root;如果為 false它呀,那么只是把 LayoutParams 設(shè)置給解析出來(lái)的 View,并返回 View棒厘。
如果 root 為 null纵穿,那么直接返回解析出來(lái)的 View。
兩個(gè)參數(shù)的 inflate 方法中第三個(gè)參數(shù)的值是取決于第二個(gè)參數(shù)的奢人,如果 root == null谓媒,那么 attachToRoot 默認(rèn)為 false,反之 attachToRoot 默認(rèn)為 true何乎。
總結(jié)一下就是:
- inflate(xmlId,null) 等價(jià)于 inflate(xmlld,null,false)句惯,只創(chuàng)建 temp 的 View 并直接返回 temp,不能正確處理我們?cè)O(shè)置的寬和高支救;
- inflate(xmlId,root) 等價(jià)于 inflate(xmlId,root,true)抢野,創(chuàng)建 View,執(zhí)行 root.addView(temp,params)各墨,返回 root指孤,能正確處理我們?cè)O(shè)置的寬和高;
- inflate(xmlId,null,true) 贬堵,只創(chuàng)建 temp 的 View 并直接返回temp恃轩,不能正確處理我們?cè)O(shè)置的寬和高;
- inflate(xmlId,root,false)黎做,創(chuàng)建 View叉跛,執(zhí)行 temp.setLayoutParams(params),返回 temp蒸殿,能正確處理我們?cè)O(shè)置的寬和高筷厘;
簡(jiǎn)單說(shuō)就是 root 不為 null挽铁,會(huì)生成 LayoutParams,xml 文件中設(shè)置的寬高有效敞掘,如果這時(shí)候 attchToRoot 為true叽掘,把解析出來(lái)的 View 添加到 root 上面返回 root
View 也有 inflate 方法,其實(shí)也是封裝了生成 LayoutInfalter 調(diào)用 inflate 方法:
public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}
在 inflate 方法里面的細(xì)節(jié)并沒(méi)有作深入探討玖雁。
1.解析 XML 的根標(biāo)簽更扁。
2.如果是 merge,調(diào)用 rInflate 進(jìn)行解析赫冬。它會(huì)把 merge 所有子 view 添加到根標(biāo)簽中浓镜。
3.如果是普通標(biāo)簽,調(diào)用 createViewFromTag 進(jìn)行解析劲厌。
4.調(diào)用 rInflate 解析 temp 根元素下的子 view膛薛。并添加到 temp 中。
參考:
Android應(yīng)用setContentView與LayoutInflater加載解析機(jī)制源碼分析