Inflater英文意思是膨脹,在
Android
中應(yīng)該是擴展的意思吧。
LayoutInflater的作用類似于 findViewById(),不同點是LayoutInflater是用來找layout文件夾下的xml布局文件,并且實例化!而 findViewById()是找具體某一個xml下的具體 widget控件(如:Button,TextView等)。
獲取它的用法有3種:
方法1:
由 LayoutInflater的靜態(tài)函數(shù): from ( Context context) 獲取:
static LayoutInflater from ( Context context);
如:
?
- LayoutInflater inflater = LayoutInflater.from( this );
- View view=inflater.inflate(R.layout.ID, null );
- //或?qū)懗桑?
- View view=LayoutInflater.from( this ).inflate(R.layout.ID, null );
LayoutInflater inflater = LayoutInflater.from(this); View view=inflater.inflate(R.layout.ID, null); //或?qū)懗桑? View view=LayoutInflater.from(this).inflate(R.layout.ID, null);
方法2:
由服務(wù)獲取:
?
- LayoutInflater inflater = (LayoutInflater)context.getSystemService
- (Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
方法3:
調(diào)用Activity的 getLayoutInflater () 函數(shù)獲取 LayoutInflater 對象。
?
setContentView和inflate區(qū)別
轉(zhuǎn): http://blog.163.com/promise_wg/blog/static/18912001420116241062211/
一般用LayoutInflater做一件事:inflate
inflate這個方法總共有四種形式(見下面),目的都是
把xml表述的layout轉(zhuǎn)化為View對象
。
其中有一個比較常用,View inflate(int resource, ViewGroup root),另三個,其實目的和這個差不多。
int resource,也就是resource/layout文件在R文件中對應(yīng)的ID,這個必須指定。
而ViewGroup root則可以是null,null時就只創(chuàng)建一個resource對應(yīng)的View,不是null時,會將創(chuàng)建的view自動加為root的child。
setContentView()一旦調(diào)用, layout就會立刻顯示UI;而
inflate只會把Layout形成一個以view類實現(xiàn)成的對象,有需要時再用setContentView(view)顯示出來
一般在activity中通過setContentView()將界面顯示出來,但是如果在非activity中如何對控件布局設(shè)置操作了,這需LayoutInflater動態(tài)加載
< TextView
android:id="@+id/tview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="ATAAW.COM"
/>
< Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/button"
android:text="按鈕"
/>
在程序中動態(tài)加載以上布局。
LayoutInflater flater =
LayoutInflater.from
(this);
View view = flater.
inflate
(R.layout.example, null);
獲取布局中的控件。
button = (Button) view.findViewById(R.id.button);//
這里的view為上面獲取的view對象
textView = (TextView)view.findViewById(R.id.tview);
LayoutInflater.inflate()將Layout文件轉(zhuǎn)換為View,專門供Layout使用的Inflater。雖然Layout也是View的子類,但在android中如果想將xml中的Layout轉(zhuǎn)換為View放入.java代碼中操作,只能通過Inflater,而不能通過findViewById()。
findViewById有兩種形式
R.layout.xx是引用res/layout/xx.xml的布局文件(inflate 方法),R.id.xx是引用布局文件里面的組件,組件的id是xx(findViewById方法)。所有的組件id都能用R.id.xx來查看,但是組件不在setContentView()里面的layout中就無法使用,Activity.findViewById()會出現(xiàn)空指針異常
a. activity中的findViewById(int id)
b. View 中的findViewById(int id)
不同點是LayoutInflater是用來找layout下xml布局文件,并且實例化!而findViewById()是找具體xml下的具體 widget控件(如:Button,TextView等)。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
