在使用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);