Android中的LayoutInflater

將一個layout文件實例化成一個View或ViewGroup就會用到LayoutInflater。
具體有兩大類

第一大類(先獲取LayoutInflater然后再inflate)

獲取LayoutInflater有三種方法(其實后兩種方法都是調用第一種方法)

  1. LayoutInflater inflater = (LayoutInflater)
    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  2. LayoutInflater inflater = getLayoutInflater();
  3. LayoutInflater inflater = LayoutInflater.from(context);

inflate方法有四種方法(主要使用前兩種,具體怎么使用放到后面講)

  1. public View inflate(int resource, ViewGroup root)
  2. public View inflate(int resource, ViewGroup root, boolean attachToRoot)
  3. public View inflate(XmlPullParser parser, ViewGroup root)
  4. 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了。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容