LayoutInflater类可以从XML文件中实例化View对象,其中涉及到XML解析,使用的是PULL解析;从标签实例化View,使用的是反射。
如何获取LayoutInflater?
为了获取LayoutInflater对象,一般不会调用其构造方法,而是调用getLayoutInflater()或getSystemService(Class)方法来获取已经和当前Context绑定的LayoutInflater对象,另外也可以使用LayoutInflater的静态方法from(Context)调用,不过这些调用方法归根结底都是调用了getSystemService(Class)获取的LayoutInflater。
首先看LayoutInflater.from(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;
}
从上面可以看出,使用了getSystemService方法获取LayoutInflater。再看Activity的getLayoutInflater方法:
public LayoutInflater getLayoutInflater() {
return getWindow().getLayoutInflater();
}
我们知道Activity的getWindow()方法会返回PhoneWindow对象,接下来看PhoneWindow的getLayoutInflater方法:
public LayoutInflater getLayoutInflater() {
return mLayoutInflater;
}
从上面的代码可以看出,直接返回了mLayoutInflater,而LayoutInflater的初始化是在PhoneWindow的构造方法中:
public PhoneWindow(Context context) {
super(context);
mLayoutInflater = LayoutInflater.from(context);
}
可以看出这儿使用的from方法构造的,但是从上面我们知道from也是通过getSystemService创建的,所以最终都是通过getSystemService()方法创建LayoutInflater对象,所以这也就是必须得提供Context参数的原因。
如何使用LayoutInflater加载View?
得到LayoutInflater对象之后,就可以调用其inflater方法加载View,inflater有好几个重载方法,可以根据需要调用不同的inflater方法。
从源码角度分析inflater方法
虽然inflater方法有多个重载方法,但是最终都会进入一个inflater方法,具体如下:
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) {
final InflateException ie = new InflateException(e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (Exception e) {
final InflateException ie = new InflateException(parser.getPositionDescription()
+ ": " + e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
return result;
}
}
首先官方文档中是这样解析三个参数以及返回值的,parser是XML的解析器;root参数是生成View层次的可选父视图(如果attachToRoot为true),或者只是简单地为返回的根布局提供LayoutParams值;attachToRoot表示加载的视图是否应该被添加到root参数;返回的View表示加载层次的根布局。如果root提供了并且attachToRoot为true,那么就是root;否则就是XML的根结点对应的View。
下面,我们就源码给出解释。首先将result置为root,然后进行XML解析,主要看try块内的代码,前面是一些范围判断,接下去首先解析第一个标签,即XML的根结点,如果是merge标签,那么按照merge的属性,必须外面有布局,所以如果root为null或者attachToRoot为false,直接抛出异常,否则调用rInflate方法,这个方法下面再看,首先看根标签不是merge的情况。
当根标签不是merge的时候,那么就进入了else语句块。首先调用createViewFromTag生成根View,下面看一下createViewFromTag的实现,代码如下:
private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) {
return createViewFromTag(parent, name, context, attrs, false);
}
从上面可以看出,又调用了createViewFromTag的一个重载方法,如下:
/**
* Creates a view from a tag name using the supplied attribute set.
* <p>
* <strong>Note:</strong> Default visibility so the BridgeInflater can
* override it.
*
* @param parent the parent view, used to inflate layout params
* @param name the name of the XML tag used to define the view
* @param context the inflation context for the view, typically the
* {@code parent} or base layout inflater context
* @param attrs the attribute set for the XML tag used to define the view
* @param ignoreThemeAttr {@code true} to ignore the {@code android:theme}
* attribute (if set) for the view being inflated,
* {@code false} otherwise
*/
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
// Apply a theme wrapper, if allowed and one is specified.
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)) {
// Let's party like it's 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, e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (Exception e) {
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name, e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
}
}
createViewFromTag方法使用提供的AttributeSet和标签名创建一个View对象。主要看try块中的代码,首先尝试使用LayoutInflater的Factory2和Factory创建视图,一般情况下这两个参数均为null,最后会进入到第204行,如果View标签是一个自定义View或者Support库中的View,那么在XML中定义时就会出现”xxx.xxx.xxx”的样式,所以就会包含”.”,就会调用createView方法,否则onCreateView方法。先看onCreateView方法,
protected View onCreateView(String name, AttributeSet attrs)
throws ClassNotFoundException {
return createView(name, "android.view.", attrs);
}
可以看到对于自带的View,createView中第二个参数为”android.view”,如果再加上标签名,就可以构成View的完整路径了;而对于含有”.”的标签名,最终也是调用createView方法,但是第二个参数为null,因为第一个参数name已经是完整路径了,比如”android.support.v4.view.ViewPager”。下面是createView的实现:
/**
* Low-level function for instantiating a view by name. This attempts to
* instantiate a view class of the given <var>name</var> found in this
* LayoutInflater's ClassLoader.
*
* <p>
* There are two things that can happen in an error case: either the
* exception describing the error will be thrown, or a null will be
* returned. You must deal with both possibilities -- the former will happen
* the first time createView() is called for a class of a particular name,
* the latter every time there-after for that class name.
*
* @param name The full name of the class to be instantiated.
* @param attrs The XML attributes supplied for this instance.
*
* @return View The newly instantiated view, or null.
*/
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
Constructor<? extends View> constructor = sConstructorMap.get(name);
if (constructor != null && !verifyClassLoader(constructor)) {
constructor = null;
sConstructorMap.remove(name);
}
Class<? extends View> clazz = null;
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
if (constructor == null) {
// Class not found in the cache, see if it's real, and try to add it
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 we have a filter, apply it to cached constructor
if (mFilter != null) {
// Have we seen this name before?
Boolean allowedState = mFilterMap.get(name);
if (allowedState == null) {
// New class -- remember whether it is allowed
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) {
// Use the same context when inflating ViewStub later.
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
return view;
} catch (NoSuchMethodException e) {
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + (prefix != null ? (prefix + name) : name), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (ClassCastException e) {
// If loaded class is not a View subclass
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Class is not a View " + (prefix != null ? (prefix + name) : name), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (ClassNotFoundException e) {
// If loadClass fails, we should propagate the exception.
throw e;
} catch (Exception e) {
final InflateException ie = new InflateException(
attrs.getPositionDescription() + ": Error inflating class "
+ (clazz == null ? "<unknown>" : clazz.getName()), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
createView方法主要就是使用反射创建View对象。至此,XML的根节点的View被创建好了,接下来继续看inflater中的代码。首先如果root不为null,那么就调用generateLayoutParams方法创建LayoutParams对象,此时如果attachToRoot为false,那么就意味着不会把根结点temp添加给root,只是使用root生成的LayoutParams,所以只是调用temp的setLayoutParams方法。然后调用rInflateChildren方法加载temp的子视图,接下来主要代码:
// 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;
}
从上面的代码可以看出,如果root不为null且attachToRoot为true,那么就将temp添加到root中;如果root为null或者attachToRoot为false,那么result就是temp,即XML的根结点。那么下面根据root和attachToRoot总结一下各种情况下的返回值:
1. 如果root为null,那么返回值是XML的根结点对应的View
2. 如果root不为null,attachToRoot为false,那么返回值是XML的根结点对应的View,但是View的LayoutParams是root生成的
3. 如果root不为null,且attachToRoot为true,那么返回值是root,XML的根结点对应的View被添加到root中
再了解了上面规则之后,先看inflate的其他几个方法:
View inflate(@LayoutRes int resource, @Nullable ViewGroup root)
View inflate(XmlPullParser parser, @Nullable ViewGroup root)
上述方法中,如果root不为null,那么其调用的最终inflate中attachToRoot为true,否则为false。
在了解了具体什么情况返回的是什么View之后,再看一下rInflateChildren方法:
/**
* Recursive method used to inflate internal (non-root) children. This
* method calls through to {@link #rInflate} using the parent context as
* the inflation context.
* <strong>Note:</strong> Default visibility so the BridgeInflater can
* call it.
*/
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
boolean finishInflate) throws XmlPullParserException, IOException {
rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}
rInflaterChildren方法用于迭代加载内部孩子,下面看rInflater方法:
/**
* Recursive method used to descend down the xml hierarchy and instantiate
* views, instantiate their children, and then call onFinishInflate().
* <p>
* <strong>Note:</strong> Default visibility so the BridgeInflater can
* override it.
*/
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("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge /> 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();
}
}
可以看到会调用createViewFromTag创建标签对应的View,再将其添加到parent中,然后再以View为父视图调用rInflateChildren方法,如此反复,直到最终解析出整个XML文档。
再看merge标签的操作,因为是merge,所以默认root是其父布局,所以直接调用了rInflate方法。
总结
针对LayoutInflater的inflate方法,需要知道各种方法中传参所带来的影响,以及最终的View。具体规则再总结一次:
1. 如果root为null,那么返回值是XML的根结点对应的View
2. 如果root不为null,attachToRoot为false,那么返回值是XML的根结点对应的View,但是View的LayoutParams是root生成的
3. 如果root不为null,且attachToRoot为true,那么返回值是root,XML的根结点对应的View被添加到root中