LayoutInflater.from(this).inflate()詳解
需求:經常需要從其他佈局引入到當前佈局中
inflate:英文翻譯膨脹的,挺貼切的
解決問題:
- 為什麼我佈局沒有顯示出來
- 為什麼我根佈局明明設定了屬性了啊,怎麼沒生效呢
- 返回給我的view是我的根佈局還是父容器呢
問題的產生是infate()引數不同導致的結果
第一種
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);
結果:
返回的view是父容器(root)佈局
item根佈局的寬高屬性生效
已經新增到父容器(root)中
第二種
root != null, attachToRoot=false
LinearLayout root = (LinearLayout) findViewById(R.id.layout); View view1 = LayoutInflater.from(this).inflate(R.layout.item, root, false);
結果:
返回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);
結果:
返回item根佈局
根佈局的寬高屬性失效
未新增到父容器(root)中
一般經驗來說:LayoutInflater.from(this).inflate(R.layout.item, null)用的最多
但是碰到要新增到列表的記得需要root,root一般就是列表控制元件,要不然寬高屬性失效,你就納悶怎麼沒顯示的呢
如果恰好解決你的問題或者學到了新知識,就打賞個買水錢唄