Android获取LayoutInflater对象的方法总结

在写Android程序时,有时候会编写自定义的View,使用Inflater对象来将布局文件解析成一个View。本文主要目的是总结获取LayoutInflater对象的方法。


1、若能获取context对象,可以有以下几种方法:

[java]  view plaincopy在CODE上查看代码片派生到我的代码片
  1. LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  2. View child = inflater.inflate(R.layout.child, null);  

or

[java]  view plaincopy在CODE上查看代码片派生到我的代码片
  1. LayoutInflater inflater = LayoutInflater.from(context);  
  2. View child = inflater.inflate(R.layout.child, null);  
[java]  view plaincopy在CODE上查看代码片派生到我的代码片
  1. </pre><p></p><pre>  
2、在一个Activity中,可以有以下方法:

[java]  view plaincopy在CODE上查看代码片派生到我的代码片
  1. View child = getLayoutInflater().inflate(R.layout.child, item, false);  
or

[java]  view plaincopy在CODE上查看代码片派生到我的代码片
  1. View view;   
  2. LayoutInflater inflater = (LayoutInflater)   getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);   
  3. view = inflater.inflate(R.layout.mylayout, null);  

方法1和方法2其实都是对context().getSystemService()的使用


3、使用View的静态方法:

[java]  view plaincopy在CODE上查看代码片派生到我的代码片
  1. View view=View.inflate(context, R.layout.child, null)  

inflate实现源码如下:

[java]  view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * Inflate a view from an XML resource.  This convenience method wraps the {@link 
  3.  * LayoutInflater} class, which provides a full range of options for view inflation. 
  4.  * 
  5.  * @param context The Context object for your activity or application. 
  6.  * @param resource The resource ID to inflate 
  7.  * @param root A view group that will be the parent.  Used to properly inflate the 
  8.  * layout_* parameters. 
  9.  * @see LayoutInflater 
  10.  */  
  11. public static View inflate(Context context, int resource, ViewGroup root) {  
  12.     LayoutInflater factory = LayoutInflater.from(context);  
  13.     return factory.inflate(resource, root);  
  14. }  
LayoutInflater.from(context)实际上是对方法1的包装,可参考以下源码:

[java]  view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * Obtains the LayoutInflater from the given context. 
  3.  */  
  4. public static LayoutInflater from(Context context) {  
  5.     LayoutInflater LayoutInflater =  
  6.             (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  7.     if (LayoutInflater == null) {  
  8.         throw new AssertionError("LayoutInflater not found.");  
  9.     }  
  10.     return LayoutInflater;  
  11. }  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值