需求:經(jīng)常需要從其他布局引入到當前布局中
inflate:英文翻譯膨脹的,挺貼切的
解決問題:
- 為什么我布局沒有顯示出來
- 為什么我根布局明明設(shè)置了屬性了啊,怎么沒生效呢
- 返回給我的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一般就是列表控件,要不然寬高屬性失效,你就納悶怎么沒顯示的呢
如果恰好解決你的問題或者學到了新知識,就點個贊