思来想去,决定还是尝试下写自己的博客,第一次写博客,有什么写得不好的地方请谅解,写得不对的地方请指教。ok!废话少说,直接进入正题!
今天想讲解一下inflate()方法动态加载布局。先说一下Android中的基本用法吧!
LayoutInflater inflater = LayoutInflater.from(context);//获取LayoutInflater对象
//加载布局,layoutID为layout文件下的布局文件名;第二个参数表示该布局要添加到哪个父布局中,若无,则置为null
View view = inflater.inflate(layoutId, null);
另外还有一种常用的方法来加载布局:
//加载布局,layoutID为layout文件下的布局文件名;第三个参数表示该布局要添加到哪个父布局中,若无,则置为null
View view = View.inflate(context, layoutId, null);
好了,如此就可以得到从res/layout/的布局view
不过,第二种方法的本质其实还是用到了第一种方法,只是将其封装起来了。
常用的例子是在ListView设置Adapter时,如果要使用自定义的item布局,就会使用到该方法。
说个题外话:以前在自定义item布局写Adapter时,发觉如果将布局中的根节点设为RelativeLayout,然后运行时就发觉报了一堆莫名其妙的错误,后来将其改为LinearLayout,就没事了,不知道是不是Android本身某个地方的bug。总之,在此只是想提醒下各位,如果哪天您在布局里将根节点设为RelativLayout,并将布局inflate()到java代码中,然后有发现运行错误退出了,不妨试下是不是出现了我所说的那种问题。
介绍完动态加载布局inflate()的常用方式后,接下来从源码的角度试着来解析下:
先看下View.inflate()的源码
public static View inflate(Context context, int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}
从此处可以看出,View.inflate()是将LayoutInflater.inflate()封装起来了。所以最终还是回到LayoutInflater的inflate(),接下来看看它的源码:
public View inflate(int resource, ViewGroup root) {
return inflate(resource, root, root != null);
}
public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
if (DEBUG) System.out.println("INFLATING from resource: " + resource);
XmlResourceParser parser = getContext().getResources().getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
该方法会先获取布局文件resource(总所周知,布局文件是xml格式)的xml的pull解析器parser(至于其具体是怎么获取的,有兴趣的童鞋可以自己去查找相关资料自己学习,在此不多讲)。然后是到了第05行处的方法inflate(parser, root, attachToRoot),源码如下:
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context)mConstructorArgs[0];
mConstructorArgs[0] = mContext;
View result = root;
try {
/***1.start***/
// Look for the root node.
//此处parser.next()理论上应该为开始标签,即type==XmlPullParser.START_TAG,
//即为根标签
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
//若不是为START_TAG,即为END_DOCUMENT,即使说为空文档
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
//得到根标签名,即一般为布局文件中的RelativeLayout或LinearLayout等。。。
final String name = parser.getName();
/***1.end***/
if (DEBUG) {
System.out.println("**************************");
System.out.println("Creating root view: "
+ name);
System.out.println("**************************");
}
//若跟标签为merge类型,则必须嵌入父布局中,即root不能空,且attachToRoot需为true
//否则抛出异常
if (TAG_MERGE.equals(name)) {
if (root == null || !attachToRoot) {
throw new InflateException(" can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
rInflate(parser, root, attrs, false);
} else {
// Temp is the root view that was found in the xml
View temp;
if (TAG_1995.equals(name)) {
temp = new BlinkLayout(mContext, attrs);
} else {
/***2.start***/
//此处只说根标签为普通布局的情况下,直接到此处
//此处创建根标签名类型的视图view,具体源代码解析稍后在解释
temp = createViewFromTag(root, name, attrs);
/***2.end***/
}
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");
}
/***3.start***/
// Inflate all children under temp
//此处是根据parser解析,然后在根视图temp中循环添加子视图,
//一般情况下,得到的temp视图即为我们所要得到的布局视图,具体源代码稍后讲解
rInflate(parser, temp, attrs, true);
/***3.end***/
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 (IOException 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.start---->1.end处的代码),然后根据根标签的类型做出不同的行为,一般直接到2.start--->2.end处的temp = createViewFromTag(root, name, attrs);创建根标签的视图temp,最后在该temp视图上继续解析parser,在temp视图中递归创建添加子视图(3.start--->3.end处的rInflate(parser, temp, attrs, true);)
先说明下是如何根据标签名创建出一个视图来,createViewFromTag()源码如下:
View createViewFromTag(View parent, String name, AttributeSet attrs) {
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
if (DEBUG) System.out.println("******** Creating view: " + name);
try {
View view;
if (mFactory2 != null) view = mFactory2.onCreateView(parent, name, mContext, attrs);
else if (mFactory != null) view = mFactory.onCreateView(name, mContext, attrs);
else view = null;
if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, mContext, attrs);
}
if (view == null) {
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
}
if (DEBUG) System.out.println("Created view is: " + view);
return view;
} catch (InflateException e) {
throw e;
} catch (ClassNotFoundException e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name);
ie.initCause(e);
throw ie;
} catch (Exception e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name);
ie.initCause(e);
throw ie;
}
}
此处的代码不多,会根据不同的工厂类和标签名来的情况来创建视图,但不管是何处的onCreateView,观看其源码,最终还是会调用22行出的createView()来创建视图,
其源代码如下:
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
/***1.start**/
//首先从内存缓冲sConstructorMap中获取类名为name的构造器
Constructor extends View> constructor = sConstructorMap.get(name);
Class extends View> clazz = null;
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
/**若构造器不存在,即还没加载过该类型的视图,就通过反射的技术获取到class对象,
* 然后获取其构造器,并存到缓存sConstructorMap中
*/
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);
//存放到缓存中
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);
}
}
}
/***1.end***/
Object[] args = mConstructorArgs;
args[1] = attrs;
/***2.start***/
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
// always use ourselves when inflating ViewStub later
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(this);
}
return view;
/***2.end***/
} catch (NoSuchMethodException e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class "
+ (prefix != null ? (prefix + name) : name));
ie.initCause(e);
throw ie;
} catch (ClassCastException e) {
// If loaded class is not a View subclass
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Class is not a View "
+ (prefix != null ? (prefix + name) : name));
ie.initCause(e);
throw ie;
} catch (ClassNotFoundException e) {
// If loadClass fails, we should propagate the exception.
throw e;
} catch (Exception e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class "
+ (clazz == null ? "" : clazz.getName()));
ie.initCause(e);
throw ie;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
此处的代码不难理解,先在1.start--->1.end处获取类的构造器,然后在2.start--->2.end出创建出实例对象并返回,即可得到根据标签名创建的视图.
好了,回到前面inflate()方法中的3.stat--->3.end处的rInflate()方法中,其源码如下:
void rInflate(XmlPullParser parser, View parent, final 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;
}
/***1.start***/
//获取到下一个标签名
final String name = parser.getName();
/***1.end***/
if (TAG_REQUEST_FOCUS.equals(name)) {
parseRequestFocus(parser, parent);
} else if (TAG_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
throw new InflateException(" cannot be the root element");
}
parseInclude(parser, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException(" must be the root element");
} else if (TAG_1995.equals(name)) {
final View view = new BlinkLayout(mContext, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflate(parser, view, attrs, true);
viewGroup.addView(view, params);
} else {
/***2.stat***/
final View view = createViewFromTag(parent, name, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflate(parser, view, attrs, true);
viewGroup.addView(view, params);
/***2.end***/
}
}
//执行到此处,说明可以退出递归,即其符视图parent已创建完毕,结束其加载
if (finishInflate) parent.onFinishInflate();
}
先看到1.start--->1.end出,是获取方法中parser的子标签名,然后根据该子标签名到2.start--->2.end处,还是根据方法createViewFromTag创建出新的子视图view,再递归rInflate创建子视图view的子视图,最后添加到父视图parent中。由于此处用来递归,可能难以理解,需要各位仁兄慢慢品味其逻辑。
到此,整个布局的加载已经完毕!