Android inflate解析
对于inflate,我相信大家都不陌生,它的作用是将一个layout.xml布局文件变为一个View对象。尤其在ListView、GridView、RecyclerView的Adapter还有组合自定义控件中,我们都会使用inflate()
方法去加载一个布局,作为每个Item的布局。这篇博客就来分析一下Android中inflate是怎样将xml文件变为View的。
使用inflate,一般是调用两个类中的方法:
-
使用
View
中的静态方法View.inflate()
public static View inflate(Context context, @LayoutRes int resource, ViewGroup root)
-
使用
LayoutInflater
中的inflate()
方法,在LayoutInflater
类中有几个重载方法public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) public View inflate(XmlPullParser parser, @Nullable ViewGroup root) public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
inflate()
方法内部调用过程
-
View#inflate()
public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { LayoutInflater factory = LayoutInflater.from(context); return factory.inflate(resource, root); }
View.inflate()
调用了LayoutInflater
中的inflate()
方法,所以上面的两个类中的方法实际是一样的。下面看一下LayoutInflater
的调用过程。 -
LayoutInflater#inflate()
// 内部调用 inflate(resource, root, root != null) public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) { return inflate(resource, root, root != null); } // 内部调用 inflate(parser, root, attachToRoot) public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) { final Resources res = getContext().getResources(); final XmlResourceParser parser = res.getLayout(resource); try { // 调用方法 return inflate(parser, root, attachToRoot); } finally { parser.close(); } } // 内部调用 inflate(resource, root, root != null) public View inflate(XmlPullParser parser, @Nullable ViewGroup root) { return inflate(parser, root, root != null); } // 最终调用方法 public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot){ // 解析xml文件,返回View对象 }
通过上面的调用过程可以看到,不管是View#inflate()
方法还是LayoutInflater#inflate()
,最终都是调用了同一个方法,那么我们就只需要接着看这个方法的解析过程就可以了。
获取 LayoutInflater
对象
在说 inflate()
的解析过程之前,我们先来看一下外部怎么调用LayoutInflater#in