`

android中LayoutInflater以及inflate

阅读更多

android中LayoutInflater以及inflate

一、LayoutInflater

LayoutInflater其实是在res/layout/下找到xml布局文件,并且将其实例化,这个和findViewById()有点相似,后者是找xml布局文件下的具体widget控件(如Button、TextView等)

作用:

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

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

 

LayoutInflater 是一个抽象类,在文档中如下声明:

public abstract class LayoutInflater extends Object   

 

获得 LayoutInflater 实例的三种方式

 

1. LayoutInflater inflater = getLayoutInflater();  //调用Activity的getLayoutInflater()

例:View toastRoot = getLayoutInflater().inflate(R.layout.toast, null);

 

2. LayoutInflater localinflater =  (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

 

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

例:View convertView = LayoutInflater.from(mContext).inflate(R.layout.activity_contact, null);

 

二、inflate

通俗的说,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)肯定会报错.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics