實例化Layout中的佈局文件(xml)

  • 什麼是LayoutInflater

  This class is used to instantiate layout XML file into its corresponding View objects.源碼分析

這個類做用是把把xml類型的佈局轉化成相應的View對象佈局

  • 在實際開發中LayoutInflater這個類仍是很是有用的,它的做用相似於findViewById()。

  不一樣點是LayoutInflater是用來找res/layout/下的xml佈局文件,而且實例化;而findViewById()是找xml佈局文件下的具體widget控件(如Button、TextView等)。spa

具體做用: 一、對於一個沒有被載入或者想要動態載入的界面,都須要使用LayoutInflater.inflate()來載入;code

      二、對於一個已經載入的界面,就可使用Activity.findViewById()方法來得到其中的界面元素。xml

 

  • LayoutInflater 實例化的三種方式
  1. LayoutInflater inflater = getLayoutInflater(); //調用Activity的getLayoutInflater()
  2. LayoutInflater localinflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //context需定義
  3. LayoutInflater inflater = LayoutInflater.from(context); //context需定義

經過源碼分析,這三種方式最終的本質都是調用了Context.getSystemService()。htm

  實例化後經過inflate方法加載具體的佈局資源。有如下幾種方式:對象

  1. public View inflate (int resource, ViewGroup root) 
  2. public View inflate (XmlPullParser parser, ViewGroup root) 
  3. public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot) 
  4. public View inflate (int resource, ViewGroup root, boolean attachToRoot)

解析:若是將root參數設置爲null,則忽略xml佈局文件中的layout_x參數,(通常狀況下選擇Null便可)blog

   若是root不爲null,而且把attachToRoot=true,那麼就會根據root生成一個佈局文件View的LayoutParam對象,而且將這個View添加到root中去,而且返回這個root的View。資源

  具體例子:開發

LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View view = inflater.inflate(R.layout.custom, null); 
EditText editText = (EditText)view.findViewById(R.id.content);
  • inflate方法與 findViewById 方法的區別
  1. inflater 是用來找 res/layout下的 xml 佈局文件,而且實例化;
  2. findViewById() 是找具體 xml 佈局文件中的具體 widget 控件(如:Button、TextView 等)。
  •  inflate方法與 SetContentView方法的區別
  1. SetContentView一旦調用, layout就會馬上顯示UI
  2. inflate只會把Layout造成一個以view類實現成的對象。有須要時再用setContentView(view)顯示出來

 程序猿必讀

相關文章
相關標籤/搜索