ViewHolder views must not be attached when created. Ensure that you are not passing ‘true‘ to the at

如果在使用RecycleView时候出现了下面异常:
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;

 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值