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

需求:经常需要从其他布局引入到当前布局中
inflate:英文翻译膨胀的,挺贴切的

解决问题:

  1. 为什么我布局没有显示出来
  2. 为什么我根布局明明设置了属性了啊,怎么没生效呢
  3. 返回给我的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一般就是列表控件,要不然宽高属性失效,你就纳闷怎么没显示的呢

如果恰好解决你的问题或者学到了新知识,就点个赞

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容