ViewHolder views must not be attached when created. Ensure that you are not passing 'true' to the at
如果在使用Recyclerview的时候出现下面的异常
ViewHolder views must not be attached when created. Ensure that you are not passing ‘true’ to the attachToRoot parameter of LayoutInflate
这说明onCreateViewHolder 方法写错了
这句话的意思是,viewHolder不予许在创建的时候添加到parent里,所以如果在onCreateViewHolder方法里使用:
// View view = inflater.inflate(R.layout.item_view, parent, true);或者
// View view = inflater.inflate(R.layout.item_view, parent);
就会报错n: ViewHolder views must not be attached when created. Ensure that you are not passing ‘true’ to the attachToRoot parameter of LayoutInflate
只要改成:
// View view = inflater.inflate(R.layout.item_view, null); 或者
// View view = inflater.inflate(R.layout.item_view, parent, false);
即可
那么这三个参数是什么意思呢?
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
第一个参数是传入的布局参数
第二个参数是这个布局的父布局
第三个就是是否要将这个布局加载到父布局里
1、如果root为null,那么第三个参数传入true和false都无影响,因为当root为null的时候就用不到attachToRoot参数,这个布局的最外层参数也就没有效果了。
2、如果root不为null
2.1 attachToRoot = true,布局的最外层属性会生效并且会添加到root中,返回的view是父布局
View result = root;
return result;
2.2 attachToRoot = false,布局会添加到root中,当布局被添加到root中的时候,布局的最外层属性会生效。返回的view是resource指定的布局
if (root == null || !attachToRoot) {
result = temp;
}
return result;
完毕(#^ . ^#)
还没有评论,来说两句吧...