LayoutInflater.from(this).inflate()詳解

需求:經(jīng)常需要從其他布局引入到當前布局中
inflate:英文翻譯膨脹的,挺貼切的

解決問題:

  1. 為什么我布局沒有顯示出來
  2. 為什么我根布局明明設(shè)置了屬性了啊,怎么沒生效呢
  3. 返回給我的view是我的根布局還是父容器呢

問題的產(chǎn)生是infate()參數(shù)不同導致的結(jié)果

第一種

root != null, attachToRoot=true(默認也是true)

LinearLayout root = (LinearLayout) findViewById(R.id.layout);
View view1 = LayoutInflater.from(this).inflate(R.layout.item, root, true);
View view2 = LayoutInflater.from(this).inflate(R.layout.item, root);

結(jié)果:
返回的view是父容器(root)布局
item根布局的寬高屬性生效
已經(jīng)添加到父容器(root)中

第二種

root != null, attachToRoot=false

LinearLayout root = (LinearLayout) findViewById(R.id.layout);
View view1 = LayoutInflater.from(this).inflate(R.layout.item, root, false);

結(jié)果:
返回item根布局
根布局的寬高屬性生效
未添加到父容器(root)中

第三種

root == null,attachToRoot=false/true

View view = LayoutInflater.from(this).inflate(R.layout.item, null, false);
View view = LayoutInflater.from(this).inflate(R.layout.item, null, true);
View view = LayoutInflater.from(this).inflate(R.layout.item, null);

結(jié)果:
返回item根布局
根布局的寬高屬性失效
未添加到父容器(root)中

一般經(jīng)驗來說:LayoutInflater.from(this).inflate(R.layout.item, null)用的最多
但是碰到要添加到列表的記得需要root,root一般就是列表控件,要不然寬高屬性失效,你就納悶怎么沒顯示的呢

如果恰好解決你的問題或者學到了新知識,就點個贊

最后編輯于
?著作權(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)容