android之LayoutInflater的获取与使用

在很多地方看见过LayoutInflater的不同用法,现将几种常用的方法总结一下。

LayoutInflater 是一个抽象类,其作用类似于findViewById(),

不同的是:LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化;

而findViewById()是找xml布局文件下的具体的控件(如Button、TextView等)。

实际使用中,

1、对于一个没有被载入或者想要动态载入的界面,需要使用LayoutInflater.inflate()来载入。

2、对于一个已经载入的界面,可以使用()this.findViewById(R.id.XXX)方法来获得其中的界面元素。

获得LayoutInflater实例的三种方式;

1、LayoutInflater inflater = getLayoutInflater();

2、LayoutInflater inflater =  (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

3、LayoutInflater inflater = LayoutInflater.from(context);

本质上来说,这三种方式是一样的,如看源码我们知道,

getLayoutInflater()其实是调用 LayoutInflater.from(context),源码:

public PhoneWindow(Context context) 
{  
    super(context);  
    mLayoutInflater = LayoutInflater.from(context);  
} 
LayoutInflater.from(context) 是调用context.getSystemService()。源码:

 public static LayoutInflater from(Context context) 
   {   
        LayoutInflater LayoutInflater =   
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);   
        if (LayoutInflater == null) {   
            throw new AssertionError("LayoutInflater not found.");   
        }   
        return LayoutInflater;   
    }

本质上都是调用(LayoutInflater)context.getSystemService()。

(LayoutInflater)context.getSystemService()的使用:

LayoutInflater inflater =(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popupwindow,(ViewGroup)findViewById(R.id.test));
这里指定了inflate()方法的第二个参数为
(ViewGroup)findViewById(R.id.test)
实际上,可以设置的null。

Tips: inflate() 方法与 findViewById() 方法不同

inflater() 是用来查找 res/layout下的xml布局文件,并且实例化

而findViewById() 是查找具体xml布局文件中的实际控件(如:Button、TextView 等)。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值