關(guān)于LayoutInflater,在開(kāi)發(fā)中常常會(huì)遇到,特別是在使用ListView的時(shí)候,這個(gè)幾近是必不可少。今天我們就1起來(lái)探討LayoutInflater的工作原理。
1般情況下,有兩種方式取得1個(gè)LayoutInflater實(shí)例:
LayoutInflater inflater1, inflater2;
inflater1 = LayoutInflater.from(this);
inflater2 = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
但是當(dāng)我們查看源碼的時(shí)候,卻發(fā)現(xiàn)這兩種實(shí)際上是1種,只不過(guò)第1種將第2種封裝了1下,我們看看from這個(gè)方法的源碼:
/**
* Obtains the LayoutInflater from the given context.
*/ 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;
}
取得LayoutInflater對(duì)象以后,我們就能夠調(diào)用inflate來(lái)取得View對(duì)象了,inflate方法的源碼以下:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) { return inflate(resource, root, root != null);
}
這里調(diào)用了1個(gè)inflate的1個(gè)重載方法,這個(gè)重載方法的最后1個(gè)參數(shù)和root有關(guān),如果我們的root為空,那末最后1個(gè)參數(shù)默許為false。我們看看這個(gè)重載方法:
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();
}
}
可以看出,先是拿到布局的xml資源,然后,取得1個(gè)XmlResourceParser 對(duì)象,最后inflate(parser, root, attachToRoot);又是調(diào)用1個(gè)重載方法:
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 { int type; while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) { } 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("can be used only with a valid " + "ViewGroup root and attachToRoot=true");
}
rInflate(parser, root, inflaterContext, attrs, false);
} else { 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);
} params = root.generateLayoutParams(attrs); if (!attachToRoot) { temp.setLayoutParams(params);
}
} if (DEBUG) {
System.out.println("-----> start inflating children");
} rInflateChildren(parser, temp, attrs, true); if (DEBUG) {
System.out.println("-----> done inflating children");
} if (root != null && attachToRoot) {
root.addView(temp, params);
} 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 { mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
}
Trace.traceEnd(Trace.TRACE_TAG_VIEW); return result;
}
}
這個(gè)方法有點(diǎn)長(zhǎng),前面都是1些簡(jiǎn)單的判斷,1般情況下(特殊情況大家可以按相應(yīng)的分支走),我們的程序會(huì)履行到final View temp = createViewFromTag(root, name, inflaterContext, attrs);這行代碼,這里創(chuàng)建了1個(gè)名為temp的view,如果我們傳進(jìn)來(lái)的根布局為null的話,那末這里拿到的就是1個(gè)根布局。我們看看這個(gè)方法的源代碼:
private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) { return createViewFromTag(parent, name, context, attrs, false);
}
好啊,這里又調(diào)用了1個(gè)它的重載方法,那我們就看看這個(gè)重載方法,注意最后1個(gè)參數(shù)恒為false。
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) { if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
} if (!ignoreThemeAttr) { final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME); final int themeResId = ta.getResourceId(0, 0); if (themeResId != 0) {
context = new ContextThemeWrapper(context, themeResId);
}
ta.recycle();
} if (name.equals(TAG_1995)) { return new BlinkLayout(context, attrs);
} try {
View view; if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, context, attrs);
} else if (mFactory != null) {
view = mFactory.onCreateView(name, context, attrs);
} else {
view = null;
} if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, context, attrs);
} if (view == null) { final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context; try { if (-1 == name.indexOf(.)) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
} return view;
} catch (InflateException e) { throw e;
} catch (ClassNotFoundException e) { final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name);
ie.initCause(e); throw ie;
} catch (Exception e) { final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name);
ie.initCause(e); throw ie;
}
}
仔細(xì)分析1下這個(gè)重載方法,發(fā)現(xiàn)里邊的mFactory2和mFactory都為null,那末程序終究其實(shí)履行了這個(gè)方法里邊的這1段:
if (view == null) { final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context; try { if (-1 == name.indexOf(.)) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
前面的判斷不用說(shuō),后面的判斷,如果name中包括.,說(shuō)明我們用的不是普通的view,有多是自定義View等等,這1條大家可以自行去研究,如果name中不包括.,那末程序會(huì)履行view = onCreateView(parent, name, attrs);,那末我們就去看看這個(gè)方法:
protected View onCreateView(View parent, String name, AttributeSet attrs)
throws ClassNotFoundException { return onCreateView(name, attrs);
} protected View onCreateView(String name, AttributeSet attrs)
throws ClassNotFoundException { return createView(name, "android.view.", attrs);
} public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
Constructorextends View> clazz = null; try { Trace.traceBegin(Trace.TRACE_TAG_VIEW, name); if (constructor == null) { clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class); if (mFilter != null && clazz != null) {
boolean allowed = mFilter.onLoadClass(clazz); if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
}
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
sConstructorMap.put(name, constructor);
} else { if (mFilter != null) { Boolean allowedState = mFilterMap.get(name); if (allowedState == null) { clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
mFilterMap.put(name, allowed); if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
} else if (allowedState.equals(Boolean.FALSE)) {
failNotAllowed(name, prefix, attrs);
}
}
}
Object[] args = mConstructorArgs;
args[1] = attrs; final View view = constructor.newInstance(args); if (view instanceof ViewStub) { final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
} return view;
} catch (NoSuchMethodException e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + (prefix != null ? (prefix + name) : name));
ie.initCause(e); throw ie;
} catch (ClassCastException e) { InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Class is not a View " + (prefix != null ? (prefix + name) : name));
ie.initCause(e); throw ie;
} catch (ClassNotFoundException e) { throw e;
} catch (Exception e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + (clazz == null ? "" : clazz.getName()));
ie.initCause(e); throw ie;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
經(jīng)過(guò)了前兩個(gè)方法的相互扯皮,最后我們來(lái)到了第3個(gè)方法上,這是最后創(chuàng)建View的地方,代碼雖然很長(zhǎng),但是大家不用怕,這里的代碼我們主要分析下面這幾行,由于大部份不會(huì)被履行到。
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException Object[] args = mConstructorArgs;
args[1] = attrs;
final View view = constructor.newInstance(args); if (view instanceof ViewStub) return view;
}traceEnd(Trace.TRACE_TAG_VIEW);
}
}
我把這個(gè)方法略微精簡(jiǎn)1下,可以看到,先是通過(guò)Java的反射機(jī)制拿到這個(gè)name所表示的布局對(duì)應(yīng)的那個(gè)Java類,然后是拿到構(gòu)造方法,最后通過(guò)構(gòu)造方法拿到1個(gè)View實(shí)例,邏輯還是比較清楚的。
好的,到這里,我們就已拿到根View了,現(xiàn)在我們?cè)倩氐缴厦嬲f(shuō)的那個(gè)inflate(…)方法中,在該方法中創(chuàng)建完temp這個(gè)View以后,接著就會(huì)履行到rInflateChildren(parser, temp, attrs, true);,里邊終究會(huì)履行到1個(gè)遞歸方法,這個(gè)方法是這樣的:
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("cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("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();
}
}
這個(gè)方法還不算長(zhǎng),進(jìn)入while循環(huán)以后,在if分支里會(huì)走到最后1個(gè)else里,這里還是先調(diào)用我們前文說(shuō)的那個(gè)createViewFromTag方法取得1個(gè)布局,然后遞歸,如果取得的這個(gè)View是個(gè)ViewGroup,那末會(huì)把它的子View添加到這個(gè)ViewGroup中,如果是普通View,那末接著循環(huán)就是了。做完這些以后,下面就和1開(kāi)始提到的root是不是為null有關(guān)了,如果root為null,那末attachToRoot這個(gè)參數(shù)為false,這個(gè)時(shí)候會(huì)履行:
if (root == null || !attachToRoot) {
result = temp;
}
然后我們解析過(guò)得到的View就會(huì)被返回,如果root不為null,那末attachToRoot這個(gè)參數(shù)默許為true,那末系統(tǒng)會(huì)履行
if (root != null && attachToRoot) {
root.addView(temp, params);
}
也就是會(huì)把root套在我們解析得到的View以外,然后返回。
好了,到這里我們的LayoutInflater基本上就分析完了.
如果大家還有甚么問(wèn)題,歡迎留言討論