Android 關於inflate
通俗的說,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
publicViewinflate(intresource,ViewGrouproot,booleanattachToRoot)
在View類中,也有inflate方法
publicstaticViewinflate(Contextcontext,intresource,ViewGrouproot)
因爲在一個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
publicViewinflate(intresource,ViewGrouproot,booleanattachToRoot)
在View類中,也有inflate方法
publicstaticViewinflate(Contextcontext,intresource,ViewGrouproot)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.