这个类用来将XML的布局文件变成一个View的类。处于性能上的考虑,从XML的布局文件生成一个View类,
这个过程是在应用的构建阶段完成的,而不是在应用运行阶段进行的。
- LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- 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)
Inflate a new view hierarchy from the specified xml resource. Throws InflateException
if there is an error.
Parameters
resource | ID for an XML layout resource to load (e.g., R.layout.main_page ) |
---|---|
root | Optional 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.