Android关于RecyclerView异常java.lang.IllegalStateException: ViewHolder views must not be attached whe...

友盟报异常,关于.RecyclerView。一般解决方法是inflater.inflate参数改为null或者false。但是现在正常的都是这么写的,也不必现,所以肯定不是

搜到一个文章:
https://github.com/CymChad/BaseRecyclerViewAdapterHelper/issues/2796

    androidx.recyclerview.widget.RecyclerView
     @NonNull
        public final VH createViewHolder(@NonNull ViewGroup parent, int viewType) {
            try {
                TraceCompat.beginSection(TRACE_CREATE_VIEW_TAG);
                final VH holder = onCreateViewHolder(parent, viewType);
                if (holder.itemView.getParent() != null) {
                    throw new IllegalStateException("ViewHolder views must not be attached when"
                            + " created. Ensure that you are not passing 'true' to the attachToRoot"
                            + " parameter of LayoutInflater.inflate(..., boolean attachToRoot)");
                }
                holder.mItemViewType = viewType;
                return holder;
            } finally {
                TraceCompat.endSection();
            }
        }

holder.itemView.getParent() != null报的异常,所以找到这个holder.itemView.getParent() ,网上找的是一般是可能在setEmptyView时出现的问题,所以找到了项目中用到了相关的

 protected View getEmptyView() {
        if (emptyView == null) {
            emptyView = LayoutInflater.from(this).inflate(R.layout.layout_loading_empty, null);
        }
        return emptyView;
    }

这个emptyView可能不为空,就做一下处理

 protected View getEmptyView() {
        ViewGroup elViewGroup = (ViewGroup) emptyView.getParent();
        if (elViewGroup != null) {
            elViewGroup.removeView(emptyView);
        }
        if (emptyView == null) {
            emptyView = LayoutInflater.from(this).inflate(R.layout.layout_loading_empty, null);
        }
        return emptyView;
    }

这样就可以了

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容