Android LayoutInflater是我们在Android App开发中特别是自定义view时候经常常用的一个类。也许你开发中没有特别注意到它,但其实我们都直接或间接的使用它了。这里主要说明Android LayoutInflater的获取方式及其inflate()参数和返回值的关系。
LayoutInflater获取
- LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- LayoutInflater layoutInflater = LayoutInflater.from(Context context)
- LayoutInflater layoutInflater = activity.getLayoutInflater();
后面2种方式最后都还是调用到getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)。
而LayoutInflater 是一个抽象类,真正实现的是policy底下的PhoneLayoutInflater。
PhoneLayoutInflater是在SystemServiceRegistry.java注册到SystemService中的:
registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
new CachedServiceFetcher<LayoutInflater>() {
@Override
public LayoutInflater createService(ContextImpl ctx) {
return new PhoneLayoutInflater(ctx.getOuterContext());
}});
- 1
- 2
- 3
- 4
- 5
- 6
LayoutInflater.inflate()方法
- View inflate(@LayoutRes int resource, @Nullable ViewGroup root)
- View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
- View inflate(XmlPullParser parser, @Nullable ViewGroup root)
- View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
其中,关于XmlPullParser 在API文档中有这样一段话:
Important For performance
reasons, view inflation relies heavily on pre-processing of XML files
that is done at build time. Therefore, it is not currently possible to
use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
大意是:基于性能考虑,Android的Layout文件在编译时候做了预处理;因此,在运行时给LayoutInflater传递一个未预处理的xml的XmlPullParser是行不通地。
LayoutInflater.inflate()的返回值
* @param root Optional view to be the parent of the generated hierarchy (if * <em>attachToRoot</em> is true), or else simply an object that * provides a set of LayoutParams values for root of the returned * hierarchy (if <em>attachToRoot</em> is false.) * @param attachToRoot Whether the inflated hierarchy should be attached to * the root parameter? If false, root is only used to create the * correct subclass of LayoutParams for the root view in the XML. * @return The root View of the inflated hierarchy. If root was supplied and * attachToRoot is true, this is root; otherwise it is the root of * the inflated XML file.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
说白了,inflate()方法的返回值取决于参数root和attachToRoot:
- if(root!=null && attachToRoo) return root;
- else return root of the inflated XML