什么是LayoutInflater

        这个类用来将XML的布局文件变成一个View的类。处于性能上的考虑,从XML的布局文件生成一个View类,

这个过程是在应用的构建阶段完成的,而不是在应用运行阶段进行的。


  1. LayoutInflater  inflate  =  (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  2. LinearLayout  layout  =  (LinearLayout) inflate.inflate(R.layout.ex01_07,null); 

findViewById是针对当前视图树的查找,而LayoutInflater是动态生成View,当你不能再当前视图树下找到View的时候,用LayoutInflater

      LayoutInflater inflate = LayoutInflater.from(this) 从给定的context中获取LayoutInflater实例   


通俗的说, inflate() 就相当于将一个xml中定义的布局找出来.
因为在一个Activity里如果直接用findViewById()的话,对应的是setConentView()的那个layout里的组件.

因此如果你的Activity里如果用到别的layout,比如对话框上的layout,你还要设置对话框上的layout里的组件(像图片ImageView,文字TextView)上的内容,你就必须用inflate()先将对话框上的layout找出来,然后再用这个layout对象去找到它上面的组件,如:

View view = View.inflate(this, R.layout.dialog_layout, null);
TextView dialogTV = (TextView) view.findViewById(R.id.dialog_tv);
dialogTV.setText("abcd");

如果组件R.id.dialog_tv是对话框上的组件,而你直接用this.findViewById(R.id.dialog_tv)肯定会报错.
View.inflate() 与 inflate.inflate(R.layout.ex01_07,null) 是一样的,而且要更简单一些.


public View inflate (int resource, ViewGroup root)
Since: API Level 1

Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error.

Parameters
resourceID for an XML layout resource to load (e.g., R.layout.main_page)
rootOptional view to be the parent of the generated hierarchy.
Returns
  • The root View of the inflated hierarchy. If root was supplied, this is the root View; otherwise it is the root of the inflated XML file.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值