RecyclerView The specified child already has a parent. You must call removeView() on the child's pa

在尝试向RecyclerView添加视图时遇到了错误:'The specified child already has a parent.',通过设置LayoutInflater的inflate方法最后一个参数为false,避免将视图添加到父布局,解决了这个问题。具体做法是使用LayoutInflater.from(context).inflate(layoutId, parent, false)。" 125976070,13698307,GC-MS技术在医药、食品与环境分析中的应用,"['医药分析', '食品科学', '环境科学', '分析化学', '检测技术']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

inflat最后一个参数为false即可LayoutInflater.from(context).inflate(layoutId, parent,false)

今天在做一个小列表的时候,本来以为分分钟解决的事遇到这个错误

定位到 at android.support.v7.widget.RecyclerView$5.addView(RecyclerView.java:638)

就是addView的代码 此方法是ViewGroup的,那必然是item是有parent导致的看了半天

  @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(context).inflate(layoutId, parent));
    }

也就这inflate方法可能有问题,因为在这里加载的item嘛,一看方法有个重载的方法

inflate(@android.support.annotation.LayoutRes int resource,
                                 @android.support.annotation.Nullable android.view.ViewGroup root,
                                 boolean attachToRoot)
再看刚用的方法inflate(@LayoutRes int resource, @Nullable ViewGroup root)

 public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
    }
奶奶的原来不传 attachToRoot 并且root不为null 直接传的true,直接把parent当成item的爸爸。这尼玛。。。

果断换成

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(context).inflate(layoutId, parent,false));
    }

然后就可以了




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值