關于LayoutInflater,在開發中常常會遇到,特別是在使用ListView的時候,這個幾近是必不可少。今天我們就1起來探討LayoutInflater的工作原理。
1般情況下,有兩種方式取得1個LayoutInflater實例:
LayoutInflater inflater1, inflater2;
inflater1 = LayoutInflater.from(this);
inflater2 = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
但是當我們查看源碼的時候,卻發現這兩種實際上是1種,只不過第1種將第2種封裝了1下,我們看看from這個方法的源碼:
/**
* 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對象以后,我們就能夠調用inflate來取得View對象了,inflate方法的源碼以下:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) { return inflate(resource, root, root != null);
}
這里調用了1個inflate的1個重載方法,這個重載方法的最后1個參數和root有關,如果我們的root為空,那末最后1個參數默許為false。我們看看這個重載方法:
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個XmlResourceParser 對象,最后inflate(parser, root, attachToRoot);又是調用1個重載方法:
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;
}
}
這個方法有點長,前面都是1些簡單的判斷,1般情況下(特殊情況大家可以按相應的分支走),我們的程序會履行到final View temp = createViewFromTag(root, name, inflaterContext, attrs);這行代碼,這里創建了1個名為temp的view,如果我們傳進來的根布局為null的話,那末這里拿到的就是1個根布局。我們看看這個方法的源代碼:
private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) { return createViewFromTag(parent, name, context, attrs, false);
}
好啊,這里又調用了1個它的重載方法,那我們就看看這個重載方法,注意最后1個參數恒為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;
}
}
仔細分析1下這個重載方法,發現里邊的mFactory2和mFactory都為null,那末程序終究其實履行了這個方法里邊的這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;
}
}
前面的判斷不用說,后面的判斷,如果name中包括.,說明我們用的不是普通的view,有多是自定義View等等,這1條大家可以自行去研究,如果name中不包括.,那末程序會履行view = onCreateView(parent, name, attrs);,那末我們就去看看這個方法:
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);
}
}
經過了前兩個方法的相互扯皮,最后我們來到了第3個方法上,這是最后創建View的地方,代碼雖然很長,但是大家不用怕,這里的代碼我們主要分析下面這幾行,由于大部份不會被履行到。
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);
}
}
我把這個方法略微精簡1下,可以看到,先是通過Java的反射機制拿到這個name所表示的布局對應的那個Java類,然后是拿到構造方法,最后通過構造方法拿到1個View實例,邏輯還是比較清楚的。
好的,到這里,我們就已拿到根View了,現在我們再回到上面說的那個inflate(…)方法中,在該方法中創建完temp這個View以后,接著就會履行到rInflateChildren(parser, temp, attrs, true);,里邊終究會履行到1個遞歸方法,這個方法是這樣的:
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();
}
}
這個方法還不算長,進入while循環以后,在if分支里會走到最后1個else里,這里還是先調用我們前文說的那個createViewFromTag方法取得1個布局,然后遞歸,如果取得的這個View是個ViewGroup,那末會把它的子View添加到這個ViewGroup中,如果是普通View,那末接著循環就是了。做完這些以后,下面就和1開始提到的root是不是為null有關了,如果root為null,那末attachToRoot這個參數為false,這個時候會履行:
if (root == null || !attachToRoot) {
result = temp;
}
然后我們解析過得到的View就會被返回,如果root不為null,那末attachToRoot這個參數默許為true,那末系統會履行
if (root != null && attachToRoot) {
root.addView(temp, params);
}
也就是會把root套在我們解析得到的View以外,然后返回。
好了,到這里我們的LayoutInflater基本上就分析完了.
如果大家還有甚么問題,歡迎留言討論