Android LayoutInflater的获取及inflate()参数和返回值
16lz
2021-01-23
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
更多相关文章
- Android Studio打包生成Jar包的方法(亲测可用)
- Android之Activity之间的数据通信方式大全(二)
- Android更新UI的方法
- 最全面总结 Android WebView与 JS 的交互方式
- Eclipse中编译Android工程时出现的问题解决方法。
- Android studio获取证书指纹 (SHA1)的方法
- Android中为APP创建快捷方式的原理(自己的理解)