前言
最近又遇到RecyclerView的item最外层布局参数失效的问题,之前都没有去了解真正的原因,现在正好有空探寻一下这个问题,就从了解源码开始吧。
View的inflate()
平时我经常使用View.inflate(),它是View的一个静态方法,看到源码:
public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}
其中调用了LayoutInflater的静态方法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;
}
这里根据上下文,从系统获取了一个LayoutInfalter的实例对象。
LayoutInflater的infalte()
然后接着上面,用这个获取的对象去调用LayoutInfalter的inflate():
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();
}
}
其中可以看到获取了一个xml解析器,获取解析器的时候把要填充的xml的ID作为了参数,然后又去调用了一个inflate()的重载:
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, 即方法参数root
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)) {
// 如果要填充的xml根布局为merge标签
if (root == null || !attachToRoot) {
// 如果root为空或者不需要将创建出来的View添加到root中直接会抛异常
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
// 创建并填充子View
rInflate(parser, root, inflaterContext, attrs, false);
} else {
// Temp is the root view that was found in the xml
// 根据xml,创建对应的View,叫temp
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
// 如果传进来的root不为空
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// Create layout params that match root, if supplied
// 那么根据xml中配置的属性,去获取布局参数
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不需要被添加到root中,就给他设置布局参数
temp.setLayoutParams(params);
}
}
if (DEBUG) {
System.out.println("-----> start inflating children");
}
// Inflate all children under temp against its context.
// 创建并填充子View
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不为空,并且temp需要被添加到root中
// 那就把temp添加到root中
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) {
// root为空或者temp不需要被添加到root中
// 那么该方法返回的View就是temp
// 否则返回root
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;
}
}
以上的这个方法信息量很大,我写了很多中文注释在代码中。
关于方法返回值
我们可以知道,如果root为空或者我当前要创建的View不需要添加到root中,那么返回的就是我要创建的View,反之返回的是root。
外层布局失效的问题
我写的代码是这样的View view = View.inflate(context, R.layout.item_pic, null);
,然后根据函数调用链:
// 第一步:
View view = View.inflate(context, R.layout.item_pic, null);
// 第二步
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
// 就变成了infalte(R.layout.item_pic, null, false);
return inflate(resource, root, root != null);
}
……
// 最后就进入了上面的方法
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot){
……
}
因为我最初传入的root就是空啊,所以我最后只是创建了View,返回了View 但是没有给他设置布局参数,所以出现外层布局失效的问题。
那我创建RecyclerView的item时,直接把RecyclerView作为参数root传进去可以吗?答案是不行的,因为这样的话调用inflate()的时候是这样的:inflate(resource, recyclerView, true)
。然后你创建了View,并且把它添加到了RecyclerView。然而RecyclerView接收到你返回的View之后,还会自动把它添加到本身,这样又会出现重复添加的问题:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child’s parent first
最佳解决方案就是直接使用LayoutInflater:View view = LayoutInflater.from(context).inflate(R.layout.item_pic, recyclerView, false);
这样的话,回去看下inflate()中的逻辑,发现view会被设置布局参数,并且不会直接被添加到recyclerView中。
LayoutInflater的createViewFromTag()
在inflate()中使用createViewFromTag()去创建xml对应的View,以下是主要代码:
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
……
try {
View view;
// 可以设置LayoutInflater的Factory来自行解析View,默认这些Factory都为空
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) {
// 没有Factory的情况下,通过LayoutInflater的onCreateView()或者createView()去创建View
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
if (-1 == name.indexOf('.')) {
// 创建原生的View
// 会在onCreateView()的函数调用链中补充前缀"android.view."
// 最终也会调用createView()
view = onCreateView(parent, name, attrs);
} else {
// 创建自定义View
// 我们在xml里写的都是全类名,标签中包含"."
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
return view;
}
……
}
以上说到的Factory,我之前在TintContextWrapper强转Activity失败原因深度探索分析到过,当我们使用AppCompatActivity时,会设置Factory2为AppCompatViewInflater,然后View都会走AppCompatViewInflater的createView()。
LayoutInflater的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 {
// 从缓存中获取View的构造函数
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
// 如果prefix不为空,那么构造完整View路径,并且加载该类
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);
}
}
// 从Class对象中获取构造函数
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;
// 通过反射构造View
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
// Use the same context when inflating ViewStub later.
// 如果是ViewStub,延迟加载
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
return view;
}
……
}
对于创建View使用反射其实我比较疑惑,方法注释说的是这个createView()是低版本上使用的方法,用来从类加载器中加载给定的View。后来我百度了下,可能是为了实现全局换肤这种类似的操作。
LayoutInflater的rInflate()
通过createViewFromTag()创建了View之后,只是创建了根布局的View,那其中的子View呢,回顾inflate()中的代码,我们会发现rInflate()和rInflateChildren()这两个方法,rInflateChildren()调用的还是rInflate():
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");
}
// 解析inclued标签
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
// merge标签只能是根布局
// 到了这里说明不是根布局,抛出异常
throw new InflateException("<merge /> must be the root element");
} else {
// 创建View
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);
// 将创建的View加入父布局
viewGroup.addView(view, params);
}
}
if (finishInflate) {
parent.onFinishInflate();
}
}
布局优化总结
从以上的源码分析,我们其实可以得出如下结论:
用merge标签作为填充的xml的根布局时,必须指定一个父元素并且设置attachToRoot属性为true。
我们通常使用ViewStub来做预加载处理,来改善页面加载速度和提高流畅性。
include标签用来复用布局。
在分析源码到用反射创建View的时候,我发现了一篇比较不错的文章Android 中LayoutInflater(布局加载器)系列博文说明。