LayoutInflater类中的inflate方法是我们常用的一个工具,不管是自定义view还是ListView这类adapter类中,inflate方法都能帮助我们生成我们需要的view。那么inflate的原理是什么呢?下面就来分析下源码。
inflate方法有几个重载的方法,但是最后都是调用到了其中的一个方法,也就是View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean 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);
//1. 保留上一次的context对象
Context lastContext = (Context) mConstructorArgs[0];
//2.存储当前inflate的context对象
mConstructorArgs[0] = inflaterContext;
View result = root;
try {
// Look for the root node.
int type;
//3.找到第一个START_TAG
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();
...
//4.处理merge标签
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
//5.创建xml中的view对象
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
//6.获取root中默认的layoutParams
params = root.generateLayoutParams(attrs);
//7.如果不需要add到root中
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
...
// Inflate all children under temp against its context.
//8.处理其他的子view
rInflateChildren(parser, temp, attrs, true);
...
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
if (root != null && attachToRoot) {
//9.addview到rootview中去
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;
}
}
在代码1处,用到了一个成员变量mConstructorArgs,这是一个大小为2的数组,用来存储view构造中需要用到两个对象:context和attributeSet.在代码3处,通过一个while循环处理,找到xml中的第一个start_tag,也就是我们定义的root view。在代码4处,这里主要用来处理xml定义的<merge>
标签,这里不作赘述。在代码5处,通过createViewFromTag方法创建了view,也就是我们刚刚处理的start_tag中的view,所以真正的创建是在这个方法中,我们来看下这个方法。
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
//1.处理view标签
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
// Apply a theme wrapper, if allowed and one is specified.
//2.如果指定了Theme属性,用ContextThemeWrapper包装一下
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();
}
//3.处理blink标签
if (name.equals(TAG_1995)) {
// Let's party like it's 1995!
return new BlinkLayout(context, attrs);
}
try {
//4.mFactory,mFactory2提供了一种便捷操作让我们可以自己定制view
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) {
//5.如果没有指定上面的factory信息,那么久调用下面的机制创建view
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
//6.系统view
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
//7.自定义的view
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处,用来处理我们在xml中定义的<view class="">
标签,获取view的类名。在代码2处,如果xml中有定义theme,需要用定义的Theme来wrapper一下context,生成一个新的ContextThemeWrapper。代码3处用来处理<Blink>标签,它是一种闪烁的布局处理,不细究。在代码4处,有多个Factory,这个几个Factory的作用是LayoutInflater为我们提供了一些工厂方法,让我们自己去createView,默认都是没有这些Factory方法。从代码5处开始就是LayoutInflate的内部创建view的过程。首先保存一下context,然后判断我们的view的name中是否有.,也就是判断是否是自定义的view还是系统中的view,我们只看系统view的创建方法,也就是从代码6处开始往下看,调用onCreateView方法.
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 {
//1.检查map缓存中是否有缓存的构造器
Constructor<? extends View> constructor = sConstructorMap.get(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
//2.获取name表示的Class对象
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
//3.filter过滤class对象
if (mFilter != null && clazz != null) {
boolean allowed = mFilter.onLoadClass(clazz);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
}
//4.获取构造器
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
//5.缓存构造器
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);
}
}
}
//6.args实参,第一个参数是context
Object[] args = mConstructorArgs;
args[1] = attrs;
//7.反射获取view,调用的就是new View(Context,AttributeSet)
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) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class "
+ (prefix != null ? (prefix + name) : name));
ie.initCause(e);
throw ie;
}
...
}
代码1处检查sConstructorMap中是否有当前view的缓存的构造器,第一次处理的时候都没有,往下继续看。代码2处,使用反射,直接得到了一个view的Class对象,然后使用mFilter检查这个class对象是否是我们允许创建的Class对象,默认这个filter是不作过滤的。代码4处,通过这个class对象创建一个Constructor构造器对象,从mConstructorSignature这个对象上可以看出,使用的是public View(Context, AttributeSet)这个构造器。代码5处用来缓存这个构造器对象。代码6处用来传参,第一个参数是context已经在之前的方法中设置过,args[1]传递attributeSet对象。代码7处使用反射直接生成了View,这样最后就生成了我们需要View对象了。
回到inflate方法中,createViewFromTag已经创建了我们指定的view,接着往下看。代码6、7中,如果提供了inflate方法中第二个参数ViewGroup的话,会获取这个ViewGroup中的layoutParams,并且将它设置给刚刚生成出来的View上。处理完这些之后也就是晶晶处理了最开始的rootView,其他的子节点的view还没有处理。所以在代码8处,就是处理接下来的子view。我们大致看一下代码.
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
boolean finishInflate) throws XmlPullParserException, IOException {
rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}
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,所以不细究了。
最后在inflate方法中还需要判断是否需要将当前创建的view 加到第二个参数提供的ViewGroup中,这个判断就是第三个参数提供的。大致的流程也就是这样吧~~
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。