android學習關於LayoutInflater的使用

之前在一些應用中看到很多次使用LayoutInflater這個類,感覺這個類還是很有作用,於是查看android開發文檔,有如下對真個類的Overview:

Instantiates a layout XML file into its corresponding View objects. It is never used directly. Instead, use getLayoutInflater() or getSystemService(String) to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on. For example:

LayoutInflater inflater =(LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);

To create a new LayoutInflater with an additional LayoutInflater.Factory for your own views, you can use cloneInContext(Context) to clone an existing ViewFactory, and then call setFactory(LayoutInflater.Factory) on it to include your Factory.

For performance reasons, view inflation relies heavily on pre-processing of XML files that is done at build time. Therefore, it is not currently possible to use LayoutInflater with an XmlPullParser over a plain XML file at runtime; it only works with an XmlPullParser returned from a compiled resource (R.something file.)

然後結合一下網上的資源,做個小總結:

當我們需要在代碼中載入一個佈局,或者是要動態的載入一個佈局的時候,我們一般會用到LayoutInflater這個類,換言之,我們在通常在onCreate函數中通過setContentView中載入xml佈局。通過LayoutInflater這個類我們便可以在代碼的別的地方動態載入我們定義的xml佈局(Layout文件下的)

   首先要獲得layout的實例,有三種形式:

   1)LayoutInflater inflater = getLayoutInflater();

   2)LayoutInflater inflater =         (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

   3)LayoutInflater inflater = LayoutInflater.from(context);

   然後可以通過inflate將一個佈局填充進來,如:

   View layout = inflater.inflate(R.layout.dialog, null);

   其中在layout文件下自己定義了一個dialog.xml文件,對於inflate函數的的使用解釋,在android開發文檔上這樣解釋:Inflate a new view hierarchy from the specified xml node。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章