LayoutInflater的inflate函數用法詳解,layoutinflater用法
LayoutInflater的inflate函數用法詳解
LayoutInflater作用是將layout的xml布局檔案執行個體化為View類對象。
擷取LayoutInflater的方法有如下三種:
?
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);View layout = inflater.inflate(R.layout.main, null); LayoutInflater inflater = LayoutInflater.from(context); (該方法實質就是第一種方法,可參考原始碼)View layout = inflater.inflate(R.layout.main, null); LayoutInflater inflater = getLayoutInflater();(在Activity中可以使用,實際上是View子類下window的一個函數)View layout = inflater.inflate(R.layout.main, null); |
一直有點糾結setContentView和inflate的區別找了一些資料。寫了個小程式看了下:
?
publicclass MyInflate extendsActivity{ privateTextView tv; publicvoid OnCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); //setContentView(R.layout.main); //tv = (TextView) findViewById(R.id.tv); LayoutInflater inflate = LayoutInflater.from(this); View view = inflate.inflate(R.layout.main,null); setContentView(view); }} |
上述注釋掉的代碼和沒有注釋掉的代碼兩種情況是相同的。
區別:
setContentView()一旦調用, layout就會立刻顯示UI;而inflate只會把Layout形成一個以view類實現成的對象,有需要時再用setContentView(view)顯示出來。一般在activity中通過setContentView()將介面顯示出來,但是如果在非activity中如何對控制項布局設定作業了,這就需要LayoutInflater動態載入。
public View inflate(int Resourece,ViewGroup root)
作用:填充一個新的視圖階層從指定的XML資源檔中
reSource:View的layout的ID
root: 產生的階層的根視圖
return 填充的階層的根視圖。如果參數root提供了,那麼root就是根視圖;否則填充的XML檔案的根就是根視圖。
其餘幾個重載的inflate函數類似。