Android LayoutInflater及inflate方法
来源:互联网 发布:七日杀游戏端口被占用 编辑:程序博客网 时间:2024/05/02 13:14
相信大家对LayoutInflate都不陌生,特别在ListView的Adapter的getView方法中基本都会出现,使用inflate方法去加载一个布局,用于ListView的每个Item的布局。
LayoutInflater的作用类似于 findViewById(),不同点是LayoutInflater是用来找layout文件夹下的xml布局文件,并且实例化;而 findViewById()是找具体某一个xml下的具体 widget控件(如:Button,TextView等)。
具体区别:
- 对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入;
- 对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素
LayoutInflater 是一个抽象类,在文档中如下声明:
public abstract class LayoutInflater extends Object
一、获得 LayoutInflater 实例的三种方式
方式1. 由LayoutInflater的静态函数 from(Context context) 获取:
static LayoutInflater from(Context context);
LayoutInflater inflater = LayoutInflater.from(this);View view=inflater.inflate(R.layout.ID, null);
方式2. 由服务获取:
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);方式3. 调用Activity的getLayoutInflater() 函数获取LayoutInflater 对象:
二、调用inflate()方法
Inflate有三个参数(int resource, ViewGroup root, boolean attachToRoot)
作用:从指定的XML资源文件中填充一个新的视图层次结构
三个参数:
- resource: 布局的资源id
- root: 填充的根视图
- attachToRoot: 是否将载入的视图绑定到根视图中
这个方法重载了四种调用方式,分别为:
- public View inflate(int resource, ViewGroup root)
- 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)
这四种使用方式中,我们最常用的是第一种方式,inflate方法的主要作用就是将xml转换成一个View对象,用于动态的创建布局。虽然重载了四个方法,但是这四种方法最终调用的,还是第四种方式。第四种方式也很好理解,内部实现原理就是利用Pull解析器,对Xml文件进行解析,然后返回View对象。
具体例子请参考郭霖大神的博客:Android LayoutInflater原理分析,带你一步步深入了解View(一)
- Android LayoutInflater及inflate方法
- Android layoutinflater inflate()方法
- Android:LayoutInflater的inflate方法
- Android LayoutInflater inflate方法效率
- Android开发点点滴滴——LayoutInflater及inflate方法
- Android编程之LayoutInflater的inflate方法
- [Android]LayoutInflater的inflate方法半详解
- android LayoutInflater和inflate()方法的用法
- android-----LayoutInflater的inflate方法详解
- android LayoutInflater和inflate()方法的用法
- Android - LayoutInflater和inflate方法的用法
- android LayoutInflater和inflate()方法的用法
- Android LayoutInflater.inflate()方法的参数用途
- Android LayoutInflater.inflate()方法参数详解
- LayoutInflater 中的 inflate() 方法
- LayoutInflater的inflate方法
- LayoutInflater中的inflate方法
- LayoutInflater.inflate方法解析
- 如何将AndroidStudio项目发布到Github
- mosquitto安装与使用
- oracle学习 第一章 简单的查询语句 ——03
- BZOJ 3551 ONTAK2010 Peaks加强版 Kruskal重构树+可持久化线段树
- 读取指定文件夹中所有文件名以及文件路径,并读到matlab
- Android LayoutInflater及inflate方法
- Material Design综合实例
- 随机取10个数6
- 【太原UI设计师】Windowsphone设计的规范你知道吗?
- 304. Range Sum Query 2D - Immutable 动态规划
- odoo新API整合文档
- 实现俄罗斯方块的下落
- 第五届华中区程序设计邀请赛暨武汉大学第十四届校赛 Problem 1603 - Minimum Sum
- 深刻理解Python中的元类(metaclass)