- 什么是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等)。
具體作用: 1、對於一個沒有被載入或者想要動態載入的界面,都需要使用LayoutInflater.inflate()來載入;
2、對於一個已經載入的界面,就可以使用Activity.findViewById()方法來獲得其中的界面元素。
- LayoutInflater 實例化的三種方式
- LayoutInflater inflater = getLayoutInflater(); //調用Activity的getLayoutInflater()
- LayoutInflater localinflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //context需定義
- LayoutInflater inflater = LayoutInflater.from(context); //context需定義
通過源碼分析,這三種方式最終的本質都是調用了Context.getSystemService()。
實例化后通過inflate方法加載具體的布局資源。有以下幾種方式:
- 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)
解析:如果將root參數設置為null,則忽略xml布局文件中的layout_x參數,(一般情況下選擇Null即可)
如果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 方法的區別
- inflater 是用來找 res/layout下的 xml 布局文件,並且實例化;
- findViewById() 是找具體 xml 布局文件中的具體 widget 控件(如:Button、TextView 等)。
- inflate方法與 SetContentView方法的區別
- SetContentView一旦調用, layout就會立刻顯示UI
- inflate只會把Layout形成一個以view類實現成的對象。有需要時再用setContentView(view)顯示出來
