Inflater英文意思是膨脹,在Android中應該是擴展的意思吧。
LayoutInflater的做用相似於 findViewById(),不一樣點是LayoutInflater是用來找layout文件夾下的xml佈局文件,而且實例化!而 findViewById()是找具體某一個xml下的具體 widget控件(如:Button,TextView等)。javascript
獲取它的用法有3種:php
方法1:html
由LayoutInflater的靜態函數:from(Context context) 獲取:java
static LayoutInflater from(Context context);android
如:web
方法2:promise
由服務獲取:app
方法3:函數
調用Activity的getLayoutInflater() 函數獲取LayoutInflater 對象。佈局
setContentView和inflate區別
轉:http://blog.163.com/promise_wg/blog/static/18912001420116241062211/
通常用LayoutInflater作一件事:inflate
inflate這個方法總共有四種形式(見下面),目的都是把xml表述的layout轉化爲View對象。
其中有一個比較經常使用,View inflate(int resource, ViewGroup root),另三個,其實目的和這個差很少。
int resource,也就是resource/layout文件在R文件中對應的ID,這個必須指定。
而ViewGroup root則能夠是null,null時就只建立一個resource對應的View,不是null時,會將建立的view自動加爲root的child。
setContentView()一旦調用, layout就會馬上顯示UI;而inflate只會把Layout造成一個以view類實現成的對象,有須要時再用setContentView(view)顯示出來
通常在activity中經過setContentView()將界面顯示出來,可是若是在非activity中如何對控件佈局設置操做了,這需LayoutInflater動態加載
< 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="按鈕"
/>
在程序中動態加載以上佈局。
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文件轉換爲View,專門供Layout使用的Inflater。雖然Layout也是View的子類,但在android中若是想將xml中的Layout轉換爲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()會出現空指針異常a. activity中的findViewById(int id)b. View 中的findViewById(int id)不一樣點是LayoutInflater是用來找layout下xml佈局文件,而且實例化!而findViewById()是找具體xml下的具體 widget控件(如:Button,TextView等)。