Android中的LayoutInflater

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

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

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

  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)

第二大類(直接調(diào)用View.inflate)

View.inflate(Context context, int resource, ViewGroup root)
查看源碼會發(fā)現(xiàn),其實這個方法會調(diào)用LayoutInflater.from(context),也就是說最后還是調(diào)用
getSystemService(Context.LAYOUT_INFLATER_SERVICE)。
所以加上第一大類的三種方法,歸根結(jié)底四種方法最后都要調(diào)用
getSystemService(Context.LAYOUT_INFLATER_SERVICE)。

解釋下幾個參數(shù)

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參數(shù)就失效了。
比如layout文件中指定height為100dp,但是沒有指定root的話,是沒有效果的。
但是有時候,需要對view作一些操作再添加到父view。不指定root的話,layout參數(shù)又沒有效果。怎么辦呢?這時候就可以用下面的方法了:
inflate(int resource, ViewGroup root, boolean attachToRoot)
將attachToRoot設(shè)為false就OK了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容