LayoutInflater源码解析
LayoutInflater是开发过程中经常使用到的类,作用是将描述视图XML文件解析成View对象。
获取LayoutInflater对象有下面3种方式:
1.在Activity中调用getLayoutInflater()方法,
2.调用LayoutInflater.from(context)方法,
3.调用context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)方法。
下面我们分别分析这三种方式。
第一种方式,调用Activity的getLayoutInflater()方法。源码如下:
public LayoutInflater getLayoutInflater() {
return getWindow().getLayoutInflater();
}
这里调用了getWindow()方法获取Window对象,再调用了window对象的getLayoutInflater()方法。我们知道Activity中的window是PhoneWindow的类的实例,找到PhoneWindow类的getLayoutInflater()方法如下:
public LayoutInflater getLayoutInflater() {
return mLayoutInflater;
}
PhoneWindow中包含一个mLayoutInflater的实例,这个实例是在PhoneWindow的构造方法中创建的。
public PhoneWindow(Context context) {
super(context);
mLayoutInflater = LayoutInflater.from(context);
}
最终调用了LayoutInflater.from(context)方法。
第二种方式,调用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;
}
在LayoutInflater.from(context)方法中调用了context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)方法。
第三种方式,调用context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)方法。前两种方式最终都是调用的这个方式。而context.getSystemService()方法的最终实现是在ContextImpl类中,我们找到ContextImpl类的getSystemService(name)方法
public Object getSystemService(String name) {
return SystemServiceRegistry.getSystemService(this, name);
}
这里出现了SystemServiceRegistry类,这个类管理了所有的系统服务。通过context.getSystemService()方法最终都会访问SystemServiceRegistry的getSystemService()方法。该方法的实现如下:
public static Object getSystemService(ContextImpl ctx, String name) {
ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
return fetcher != null ? fetcher.getService(ctx) : null;
}
SYSTEM_SERVICE_FETCHERS是SystemServiceRegistry类的一个静态成员,类型是HashMap<String, ServiceFetcher<?>>。这个方法通过名称获取到一个ServiceFetcher对象,再通过ServiceFetcher.getService(context)获取到系统服务对象。
在SystemServiceFetcher的静态代码块中会初始化一些系统服务,其中就包含LayoutInfalter。
static{
~~~代码省略
registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
new CachedServiceFetcher<LayoutInflater>() {
@Override
public LayoutInflater createService(ContextImpl ctx) {
return new PhoneLayoutInflater(ctx.getOuterContext());
}
});
~~~代码省略
}
我们可以看到系统注册的LAYOUT_INFLATER_SERVICE服务实际上是PhoneLayoutInflater类的对象。
值得一提的是,Activity的父类为ContextThemeWrapper,这个类的getSystemService()方法有些特殊处理,代码如下:
public Object getSystemService(String name) {
if (LAYOUT_INFLATER_SERVICE.equals(name)) {
if (mInflater == null) {
mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this);
}
return mInflater;
}
return getBaseContext().getSystemService(name);
}
当在Activity中调用getSystemService(name)获取LayoutInflater对象时,会通过cloneInContext创建一个新的LayoutInflater对象,并且将Context关联为ContextThemeWrapper,这样在解析布局文件的时候就可以解析主题相关的属性了。
分析完创建过程,我们再看LayoutInflater的使用。一般会使用inflate方法解析xml文件,该方法有多个重载,分别如下:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
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();
}
}
public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {
return inflate(parser, root, root != null);
}
前三个重载方法最终都会调用下面这个方法
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;
}
}
该方法结构很清晰,分为一下几个步骤:
- 找到布局文件根节点
- 如果根节点是merge标签,就通过rInflate()方法解析merge节点的所有子节点。
- 如果不是merge标签就通过createViewFromTag()方法根据节点名称创建一个View对象。
- 如果方法参数root不为空,则会通过root的generateLayoutParams(attr)方法为创建的View对象生成布局参数。如果方法参数attachToRoot为false,表示不会将新创建的View对象加入到root容器中,直接将布局参数设置到View中。
- 调用rInflateChildren(parser, temp, attrs, true)方法,解析根节点的所有子节点。
- 如果root参数不为空,并且attachToRoot参数为true,会调用root.addView(temp, params)将新创建的View添加到root容器中。
- 最后将创建的View对象作为结果返回。
在这个方法内有三个比较重要的方法,分别为rInflate(),createViewFromTag()和rInflateChildren(),而rInflateChildren又会直接调用rInflate()方法。rInflater方法会递归解析xml节点,我们来看rInflate()方法的源码
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
final int depth = parser.getDepth();
int type;
boolean pendingRequestFocus = false;
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)) {
pendingRequestFocus = true;
consumeChildElements(parser);
} 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 (pendingRequestFocus) {
parent.restoreDefaultFocus();
}
if (finishInflate) {
parent.onFinishInflate();
}
}
rInflate()方法中对一些特殊标签进行处理,包括requestFocus标签,tag标签和include标签,这部分不做深入解析。我们看最后else代码段,首先会调用createViewFromTag(parent, name, context, attrs)创建View对象,再通过viewGroup.generateLayoutParams(attrs)生成view的布局参数,然后通过rInflateChildren(parser, view, attrs, true)递归解析该节点的子节点,最后调用viewGroup.addView(view, params)将创建的view对象添加到父容器中。通过递归的方式,步骤十分清晰。
我们又见到了createViewFromTag()方法,来看下这个方法的源码:
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 (Exception e) {
//省略异常处理代码
}
}
首先判断节点是否是view(注意这个view是是小写的,和View不同)节点,如果是view节点,则解析“class”属性为类名,这种方式一般用于自定义的View类是内部类的情况。
接下来有个彩蛋,如果标签名为blink,就会返回一个BlinkLayout,这个布局是LayoutInflater的内部类,作用是每500ms会隐藏显示布局内容,达到闪烁的效果。
下面会判断mFactory2和mFactory成员变量是否为空,如果为LayoutInflater设置了Facotry2或Factory,就会调用工厂的方法来创建View,否则会通过标签名中是否包含“.”(也就是标签名是否是全类名)来调用onCreateView()或createView()方法。在onCreateView()方法如下:
protected View onCreateView(String name, AttributeSet attrs)
throws ClassNotFoundException {
return createView(name, "android.view.", attrs);
}
该方法设置前缀为"android.view."后,调用了createView()方法。在LayoutInflater的子类PhoneLayoutInflater中又重写了该方法:
protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
for (String prefix : sClassPrefixList) {
try {
View view = createView(name, prefix, attrs);
if (view != null) {
return view;
}
} catch (ClassNotFoundException e) {
// In this case we want to let the base class take a crack
// at it.
}
}
return super.onCreateView(name, attrs);
}
sClassPrefixList为:
private static final String[] sClassPrefixList = {
"android.widget.",
"android.webkit.",
"android.app."
};
会尝试为标签添加这些前缀来创建View对象。也就是说如果在XML布局文件中标签没有写全类名,使用的是简写形式,例如<TextView.../>,LayoutInflater会自动补充前缀组成完整类名形式,再去解析View对象。
解析完onCreateView()方法后,再看createView()方法:
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 lastContext = mConstructorArgs[0];
if (mConstructorArgs[0] == null) {
// Fill in the context if not already within inflation.
mConstructorArgs[0] = mContext;
}
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]));
}
mConstructorArgs[0] = lastContext;
return view;
} catch (Exception e) {
//省略异常处理代码
}
}
该方法首先会中sConstructorMap缓存中通过名称获取Constructor对象,如果没有获取到,则会使用ClassLoader通过类名加载Class对象,并获取到Constructor对象加入缓存中。在加载类的时候回通过Filter来校验是否允许加载该类,如果不允许,会直接抛出错误。这个Filter也是系统提供的一个可以添加约束校验的hook点。
获取到Constructor对象后,通过反射constructor.newInstance(args)创建出View对象,并作为结果返回。如果该View是ViewStub会有些其他处理。
至此,我们已经分析出LayoutInflater最终是根据布局节点解析出视图的类名,再通过反射创建出对应的View对象的。