让我们一起了解LayoutInflater中inflate()方法吧
来源:互联网 发布:createfile串口编程 编辑:程序博客网 时间:2024/04/29 12:33
今天周五,作为程序员的我们又工作了一周了,这周开始我就纠结着到底写点什么好呢,正当我不知所措的时候,我写的代码报错了,而且是我之前遇到过的,突然我知道这周我们要聊一些什么了。
我所遇到的错误是什么呢,我猜对于大多数的初学者来说或多或少都遇到这个问题
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
那是什么造成了这个错误呢。就是我再使用LayoutInflater中的inflate()方法时遇到的。
本着不踩坑怎么能进步的原则,我就和大家一起来踩一踩这个坑。
方法头: public View inflate(@LayoutRes int resource,@Nullable ViewGroup root,boolean attachToRoot)
inflate()有两种,一种呢是有三个参数,一种是有两个参数,我们接下来分别作相应的介绍
第一种 root 不为null,attachToRoot为true
此时表示将resource指定的布局添加到root中,添加的过程中的resoruce所指定的布局的根节点的各个属性都是有效的。
View view =LayoutInflater.from(this).inflate(R.layout.linearlayout, ll,true); ll.addView(view);
如果再使用的过程中出现上面的代码,就会报 java.lang.IllegalStateException:The specified child already has a parent.You must call removeView() on the child's parent first.
的错误,因为第一行代码已经将R.layout.linearlayout添加到 ll中去了。ll.addView(view) 就属于重复添加了。
第二种 root不为null,attachToRoot 为flase时
root 不为null,而attachToRoot为false的话,表示不将第一个参数所制定的View添加到root中,好奇的同学就想知道了:如果不添加到root中,那么还要这个root有什么作用呢,root 直接传null不就可以了吗?其实事情并不是这样的。这里就要谈到另外的知识了,我们给控件指定的layout_width和layout_height到底是什么意思呢?该属性标识一个控件在一个容器中的大小,所以这个控件必须在容器中,这个属性才有意义,否则是无意义的。这也就是说如果我没有指定root,inflate布局的根节点的layout_width和layout_height属性将会失效(因为这个时候linearlayout将不处于任何容器中,那么它的根节点的宽高自然会失效)。如果我想让linearlayout的根节点有效,又不想让其处于某一个容器中,那么我就可以设置root不为null,而attachToRoot为false。当我们在使用RecycleView的过程中,item布局的layout_width或者layout_height属性会失效,极有可能就是没有设置root参数。
第三种 root为null attachToRoot为ture/flase
当root为null表示不需要将第一个参数所指定的布局添加到任何容器中,同时也意味着第一个参数所指定布局的layout_width和layout_height属性将会失效
两个参数的inflate方法
先看一下源码,其实就是调用了三个参数的方法
两个参数的inflate方法分为如下两种情况:
1 root 为null,等同于第三种所描述的情况
2 root 不为null,等同于第一种所描述的情况
1 0
- 让我们一起了解LayoutInflater中inflate()方法吧
- LayoutInflater中inflate方法详解
- LayoutInflater中inflate方法的简单使用
- LayoutInflater 中的 inflate() 方法
- Android layoutinflater inflate()方法
- LayoutInflater的inflate方法
- LayoutInflater中的inflate方法
- LayoutInflater.inflate方法解析
- LayoutInflater的inflate方法
- LayoutInflater.inflate方法解析
- LayoutInflater.inflate方法解析
- LayoutInflater的inflate方法
- LayoutInflater.inflate方法浅析
- LayoutInflater.inflate方法解析
- LayoutInflater.inflate() 方法剖析
- LayoutInflater.inflate方法解析
- LayoutInflater.inflate()方法解析
- LayoutInflater#inflate()方法详解
- JSON-各种type嵌套
- Intel GPA
- table方法实现图片自适应及脚本方法
- GCD定时器示例代码
- N皇后问题 c/c++
- 让我们一起了解LayoutInflater中inflate()方法吧
- Codeforces Round #400 D. The Door Problem (建图+搜索)
- 入门训练(4)
- 如何往anroid源码中移入一个像Settings或其他一开机就已经存在且不可卸载的app
- oracle常用语法
- PHP+JavaScript 实现图片无刷新上传
- android studio 安装
- ZOJ Problem Set
- 文章标题