Android LayoutInflater的获取及inflate()参数和返回值

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());
            }});

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.

说白了,inflate()方法的返回值取决于参数root和attachToRoot:

  • if(root!=null && attachToRoo) return root;
  • else return root of the inflated XML
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值