一.概述:LayoutInflater 布局渲染器,根据layout生成一个View 通俗的讲就是将我们layout中的xml文件转换成我们的代码中的view.
二.常用的方法:
1.inflater.from(this).inflate(resource, root);
2.inflater.from(this).inflate(resource, root, attachToRoot);
参数解析:
a.int resource 我们所需要渲染的layout的id
b.ViewGroup root 一个容器:这个容器的作用究竟是什么?看源码:
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);
}
}
第8行和第12行我们找到了答案:为layout提供LayoutParams用于确定layout的大小。
为什么要提供LayoutParams:因为view在onMeasure()确定自己的大小的时候需要父容器ViewGroup提供一个相应的LayoutParams来确定子View的大小。
一句话:父容器影响子View的大小。这个可以在onMeasure()中充分的体会到
c.boolean attachToRoot 是否将我们所渲染的布局添加的root里面,也就是说 是否给我们渲染的布局添加一个父容器(root),添加为父容器之后就不需要为ziview提供LayoutParams了
三.渲染流程
public View inflate(int resource, 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();
}
}
第2行,获取资源对象,第8行根绝layout资源id得到对应的xml资源解析器,第10行,调用inflate(parser, root, attachToRoot);生成View 并返回。
我们继续来分析inflate(parser, root, attachToRoot);方法:
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) {
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 {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
}
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
return result;
}
}
第6行获取我们布局的属性(这里可以提醒一下大家 我们可以自定义LayoutInflater,获取view的自定义属性值):
final AttributeSet attrs = Xml.asAttributeSet(parser);
然后获取xml中的标签名字调用createViewFromTag方法(第42行)生成root view:
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
第65行渲染所有的子view:
rInflateChildren(parser, temp, attrs, true);
继续来分析 createViewFromTag(root, name, inflaterContext, attrs);方法:
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);
ie.initCause(e);
throw ie;
} catch (Exception e) {
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name);
ie.initCause(e);
throw ie;
}
}
看到这里我们会发现在try代码片中 会出现几个Factory对象,如果某一个Factory不为空就根据该Factory.onCreateView(parent, name, context, attrs);方法渲染创建view ,看了一下这几个Factory默认都是为空的,也就是说我们可以自定义自己的Factory来用自己的逻辑解析xml。如果所有的Factory都是null就(第41的onCreateView()或者43行的createView)调用系统的方法创建view。最后我们发现 第41行最后还是调用的第43行方法的实现执行的,看:
View createView(String name, String prefix, AttributeSet attrs)
这里就是我们最终的类的解析方法了,看源码我们是通过反射实现的,prefix这个参数就是我们标签的前缀,通过他和标签名字name拼接之后在反射创建我们的View类,再看
void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs,
boolean finishInflate, boolean inheritContext) {
final View view = createViewFromTag(parent, name, attrs, inheritContext);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflate(parser, view, attrs, true, true);
viewGroup.addView(view, params);
}
看第4行这里依然调用了createViewFromTag()方法,第7行却调用了自己,这里有没有很激动,两个字 递归搞定,最后我们回过头来总结一下究竟如何实现自定义的LayoutFlater:
1. 创建XXXFlater继承LayoutInflater。
2.在XXXFlater中创建自己的XXXFactory implements LayoutInflater.Factory
3.可以在构造方法中调用setFactory()将我们自己的factory设置给XXXFlater
4.最后实现XXXFactory.onCreateView(String name, Context context,AttributeSet attrs)方法