Android LayoutInflater了解及使用

LayoutInflater(布局加载器)

布局加载器的作用简要来说就是 将xml文件定义的View转化成View对象实例

有三种获得实例的方法:

  1. LayoutInflater LayoutInflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  2. LayoutInflater layoutInflater = LayoutInflater.from(context);
  3. LayoutInflater layoutInflater = getLayoutInflater();

注:第一种方法获取系统提供的布局加载器,第二种方法是第一个方法精简版,第三种适用于可视窗口的getLayoutInflater(),比如activity

获取到对象了,我们要怎么用呢:

inflate

inflate有多个重载方法

  • public View inflate(int resource, boolean attachToRoot)
  • public View inflate(int resource, ViewGroup root, boolean attachToRoot)
  • public View inflate(XmlPullParser parser, ViewGroup root)
  • public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)

这些方法最终调用的还是最后一个方法,我们不管,我们拿来用就行。

参数

  1. resource: 这就是要加载的xml文件。也就是 R.layout.*
  2. root: 包裹被载入的xml布局的根布局
  3. attachToRoot: 决定参数2如何布局,这是个boolean类型。当它为true时,加载的xml将会在外层再裹上一层的root的布局。如果它为 false 时,加载的layout最外层的width和height将会和root的一样。也表示你写的width和height将会无效。

注! 当root 为null时,如下。加载的layout的width和height将会是默认的布局。
public View inflate(R.layout.XXX,null)

如需深入了解LayoutInflater,请移步LayoutInflater源码解析

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值