ayoutInflater和findViewById() 的區別


一、介紹
LayoutInflater作用類似於findViewById()。
具體作用:
1、LayoutInflater是在res/layout/下的xml佈局文件,對於一個沒有被載入或者想要動態載入的界面,都需要使用LayoutInflater.inflate()來載入;
2、findViewById()是對於已經載入的界面,就可以使用Activity.findViewById()方法來獲得其中的具體widget控件(如Button、TextView等)。

二、LayoutInflater 介紹-實例化

獲得 LayoutInflater 實例的三種方式
1. LayoutInflater inflater = getLayoutInflater();//調用Activity的getLayoutInflater() 
2. LayoutInflater inflater = LayoutInflater.from(context);  
3. LayoutInflater inflater =  (LayoutInflater)context.getSystemService
                              (Context.LAYOUT_INFLATER_SERVICE);
其實,這三種方式本質是相同的,最後調用的都是:
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
即本質是都是調用的Context.getSystemService()。

三、inflate 方法
通過 sdk 的 api 文檔,可以知道該方法有以下幾種過載形式,返回值均是 View 對象,如下:
public View inflate (int resource, ViewGroup root) 
public View inflate (XmlPullParser parser, ViewGroup root)
public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)  
public View inflate (int resource, ViewGroup root, boolean attachToRoot)
參數解釋:
resource:需要加載佈局文件的id,意思是需要將這個佈局文件中加載到Activity中來操作。
root:需要附加到resource資源文件的根控件,就是inflate()會返回一個View對象,如果第三個參數attachToRoot爲true,就將這個root作爲根對象返回,否則僅僅將這個root對象的LayoutParams屬性附加到resource對象的根佈局對象上,也就是佈局文件resource的最外層的View上,比如是一個LinearLayout或者其它的Layout對象。如果提供root(不傳null)時,返回值其實就是這個root,這個方法就是把xml解析成view之後掛載這個root下。如果傳null(不提供root),返回值也是View,它就是xml佈局裏面的根節點

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