標籤:
通俗的說,inflate就相當於將一個xml中定義的布局找出來.
因為在一個Activity裡如果直接用findViewById()的話,對應的是setConentView()的那個layout裡的組件.
因此如果你的Activity裡如果用到別的layout,比如對話方塊上的layout,你還要設定對話方塊上的layout裡的組件(像圖片ImageView,文字TextView)上的內容,你就必須用inflate()先將對話方塊上的layout找出來,然後再用這個layout對象去找到它上面的組件,如:
Viewview=View.inflate(this,R.layout.dialog_layout,null);
TextViewdialogTV=(TextView)view.findViewById(R.id.dialog_tv);
dialogTV.setText("abcd");
如果組件R.id.dialog_tv是對話方塊上的組件,而你直接用this.findViewById(R.id.dialog_tv)肯定會報錯.
三種方式可以產生LayoutInflater:
LayoutInflaterinflater=LayoutInflater.from(this);
LayoutInflaterinflater=getLayoutInflater();
LayoutInflaterinflater=(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
然後調用inflate方法將xml布局檔案轉成View
LayoutInflater layoutInflater = LayoutInflater.from(DialogActivity.this);
// 得到自訂對話方塊
final View dialogView = layoutInflater.inflate(R.layout.dialog_login, null);
publicViewinflate(intresource,ViewGrouproot,booleanattachToRoot)
在View類中,也有inflate方法
publicstaticViewinflate(Contextcontext,intresource,ViewGrouproot)
引自:http://android.tgbus.com/Android/tutorial/201104/348009.shtml
Android——inflate 將一個xml中定義的布局找出來