Android(安卓)Inflate 的使用
16lz
2021-01-25
在使用View.Inflate(context,resid,root)创建recyclerview item布局时,根布局的margin,pading都没有起作用.
看了它其中的源码使用的是LayoutInflater.from().inflate(),层层跟进发现其中有一段逻辑:public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {.......省略代码 final View temp = createViewFromTag(root, name, inflaterContext, attrs); ViewGroup.LayoutParams params = null; if (root != null) { // Create layout params that match root, if supplied params = root.generateLayoutParams(attrs); if (!attachToRoot) { // Set the layout params for temp if we are not // attaching. (If we are, we use addView, below) temp.setLayoutParams(params); } } // We are supposed to attach all the views we found (int temp) // to root. Do that now. if (root != null && attachToRoot) { root.addView(temp, params); }
.......省略代码 return result; }}
也就是说,root!=null && attachToRoot==true,会将布局view添加到内部,作为它的父view,否则不会设置布局的layoutparams,但是如果我们在使用recyclerview创建item布局时并不需要添加到父view怎么办?
可以看到attachToRoot(是否附加到根布局)只需将这个参数传false,布局将不会添加到root中,并且还会设置布局的layoutparams。
调用:
LayoutInflater.from(context).inflate(R.layout.item_layout,parent,false);
更多相关文章
- 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
- android ImageView实现圆角(xml实现方法)
- RadioGroup组与onCheckedChanged事件
- listview中加入listbutton
- android中使用开源项目做出上拉、下拉刷新功能
- Android(安卓)keep screen on 方法
- Android源码编译开启ccache缓存
- 安卓EditText控件底部红线如何解决?
- 安卓学习笔记之自定义ContentProvider