Android开发之获取LayoutInflater对象的方法总结
本文实例讲述了Android开发之获取LayoutInflater对象的方法。分享给大家供大家参考,具体如下:
在写Android程序时,有时候会编写自定义的View,使用Inflater对象来将布局文件解析成一个View。本文主要目的是总结获取LayoutInflater对象的方法。
1、若能获取context对象,可以有以下几种方法:
LayoutInflaterinflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); Viewchild=inflater.inflate(R.layout.child,null);
或者:
LayoutInflaterinflater=LayoutInflater.from(context); Viewchild=inflater.inflate(R.layout.child,null);
2、在一个Activity中,可以有以下方法:
Viewchild=getLayoutInflater().inflate(R.layout.child,item,false);
或者:
Viewview; LayoutInflaterinflater=(LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); view=inflater.inflate(R.layout.mylayout,null);
方法1和方法2其实都是对context().getSystemService()的使用
3、使用View的静态方法:
Viewview=View.inflate(context,R.layout.child,null)
inflate实现源码如下:
/**
*InflateaviewfromanXMLresource.Thisconveniencemethodwrapsthe{@link
*LayoutInflater}class,whichprovidesafullrangeofoptionsforviewinflation.
*
*@paramcontextTheContextobjectforyouractivityorapplication.
*@paramresourceTheresourceIDtoinflate
*@paramrootAviewgroupthatwillbetheparent.Usedtoproperlyinflatethe
*layout_*parameters.
*@seeLayoutInflater
*/
publicstaticViewinflate(Contextcontext,intresource,ViewGrouproot){
LayoutInflaterfactory=LayoutInflater.from(context);
returnfactory.inflate(resource,root);
}
LayoutInflater.from(context)实际上是对方法1的包装,可参考以下源码:
/**
*ObtainstheLayoutInflaterfromthegivencontext.
*/
publicstaticLayoutInflaterfrom(Contextcontext){
LayoutInflaterLayoutInflater=
(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(LayoutInflater==null){
thrownewAssertionError("LayoutInflaternotfound.");
}
returnLayoutInflater;
}
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》、《Android控件用法总结》、《Android短信与电话操作技巧汇总》及《Android多媒体操作技巧汇总(音频,视频,录音等)》
希望本文所述对大家Android程序设计有所帮助。
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短