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

android学习关于LayoutInflater的使用

2013-06-04 22:22 405 查看
之前在一些应用中看到很多次使用LayoutInflater这个类,感觉这个类还是很有作用,于是查看android开发文档,有如下对真个类的Overview:
Instantiates a layout XML file into its corresponding
View
objects. It is never used directly. Instead, use
getLayoutInflater()
or
getSystemService(String)
to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on. For example:
LayoutInflater inflater =(LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
To create a new LayoutInflater with an additional
LayoutInflater.Factory
for your own views, you can use
cloneInContext(Context)
to clone an existing ViewFactory, and then call
setFactory(LayoutInflater.Factory)
on it to include your Factory.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; it only works with an XmlPullParser returned from a compiled resource (R.something file.)然后结合一下网上的资源,做个小总结:
当我们需要在代码中载入一个布局,或者是要动态的载入一个布局的时候,我们一般会用到LayoutInflater这个类,换言之,我们在通常在onCreate函数中通过setContentView中载入xml布局。通过LayoutInflater这个类我们便可以在代码的别的地方动态载入我们定义的xml布局(Layout文件下的)
首先要获得layout的实例,有三种形式:
1)LayoutInflater inflater = getLayoutInflater();
2)LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
3)LayoutInflater inflater = LayoutInflater.from(context);
然后可以通过inflate将一个布局填充进来,如:
View layout = inflater.inflate(R.layout.dialog, null);
其中在layout文件下自己定义了一个dialog.xml文件,对于inflate函数的的使用解释,在android开发文档上这样解释:Inflate a new view hierarchy from the specified xml node。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: