Android(安卓)LayoutInflater的获取及inflate()参数和返回值
16lz
2021-12-04
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() { @Override public LayoutInflater createService(ContextImpl ctx) { return new PhoneLayoutInflater(ctx.getOuterContext()); }});
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 * attachToRoot is true), or else simply an object that * provides a set of LayoutParams values for root of the returned * hierarchy (if attachToRoot 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.
说白了,inflate()方法的返回值取决于参数root和attachToRoot:
- if(root!=null && attachToRoo) return root;
- else return root of the inflated XML
更多相关文章
- 浅谈Java中Collections.sort对List排序的两种方法
- Python list sort方法的具体使用
- python list.sort()根据多个关键字排序的方法实现
- 【阿里云镜像】切换阿里巴巴开源镜像站镜像——Debian镜像
- Android解析WindowManagerService(一)WMS的诞生
- Android中JNI的使用方法
- android关于activity的组成
- Android(安卓)Studio打包生成Jar包的方法(亲测可用)
- android屏幕旋转时,Activity不重新调用onCreate的方法