轉載:http://hi.baidu.com/aspxdiyer/item/5879980402843519eafe388f
一、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)肯定會報錯.