您的位置:首页 > 移动开发 > Android开发

Android LayoutInflater了解及使用

2016-10-13 17:45 501 查看

LayoutInflater(布局加载器)

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

有三种获得实例的方法:

LayoutInflater LayoutInflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

LayoutInflater layoutInflater = LayoutInflater.from(context);

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)

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

参数

resource: 这就是要加载的xml文件。也就是 R.layout.*

root: 包裹被载入的xml布局的根布局

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源码解析
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: