將一個layout文件實例化成一個View或ViewGroup就會用到LayoutInflater。
具體有兩大類
第一大類(先獲取LayoutInflater然后再inflate)
獲取LayoutInflater有三種方法(其實后兩種方法都是調用第一種方法)
- LayoutInflater inflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE); - LayoutInflater inflater = getLayoutInflater();
- LayoutInflater inflater = LayoutInflater.from(context);
inflate方法有四種方法(主要使用前兩種,具體怎么使用放到后面講)
- public View inflate(int resource, ViewGroup root)
- public View inflate(int resource, ViewGroup root, boolean attachToRoot)
- public View inflate(XmlPullParser parser, ViewGroup root)
- public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)
第二大類(直接調用View.inflate)
View.inflate(Context context, int resource, ViewGroup root)
查看源碼會發現,其實這個方法會調用LayoutInflater.from(context),也就是說最后還是調用
getSystemService(Context.LAYOUT_INFLATER_SERVICE)。
所以加上第一大類的三種方法,歸根結底四種方法最后都要調用
getSystemService(Context.LAYOUT_INFLATER_SERVICE)。
解釋下幾個參數
resource:layout文件
root:被inflate的view的父view
attachToRoot:是否添加到父view。如果為true,就不需要通過addView來添加到父view。
注意點
通過源碼查看root的解釋
A view group that will be the parent. Used to properly inflate the layout_* parameters.
也就是說沒有指定root的話,layout參數就失效了。
比如layout文件中指定height為100dp,但是沒有指定root的話,是沒有效果的。
但是有時候,需要對view作一些操作再添加到父view。不指定root的話,layout參數又沒有效果。怎么辦呢?這時候就可以用下面的方法了:
inflate(int resource, ViewGroup root, boolean attachToRoot)
將attachToRoot設為false就OK了。