ndroid中View.inflate()

来源:互联网 发布:js push json 编辑:程序博客网 时间:2024/05/29 14:39
Inflate可用于将一个xml中定义的布局控件找出来.
  因为在一个Activity里如果直接用findViewById()的话,对应的是setConentView()的那个layout里的组件。因此如果当前Activity里需要用到别的layout(xml文件),比如对话框上的layout,这时还要设置对话框上的layout里的组件(像图片ImageView,文字TextView)上的内容,所以,就必须用inflate()先将对话框的layout找出来,然后再用这个layout对象去找到它上面的组件,如:
  View view=View.inflate(this,R.layout.dialog_layout,null);
  TextViewdialogTV=(TextView)view.findViewById(R.id.dialog_tv);
  dialogTV.setText("abcd");
  如果直接用this.findViewById(R.id.dialog_tv)肯定会报错.
生成LayoutInflater的方法:
上文示例中写的方法来创建inflate一般不常用,一般通过LayoutInflater来创建inflate。主要有三种方式可以生成LayoutInflater:
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.main, null);
 
LayoutInflater inflater = LayoutInflater.from(context);