上下滚动RecyclerView时ChipGroup重复添加相同Material Chips问题咨询
问题原因
这是RecyclerView的视图复用机制导致的:滚动出屏幕的列表项对应的ViewHolder会被回收复用给新移入屏幕的列表项,你每次调用onBindViewHolder绑定数据时,都会往ChipGroup新增Chip,但没有清除ViewHolder中ChipGroup之前残留的旧Chip,所以每复用一次ViewHolder就会多新增一批Chip,滚动次数越多Chip数量越多。
修复方案
只需要在onBindViewHolder中添加新Chip前,先清空ChipGroup内已有的所有子View即可,同时如果你的Post类存储了对应标签列表,还可以遍历标签列表动态生成对应Chip,修改后的代码如下:
override fun onBindViewHolder(holder: PostViewHolder, position: Int) { val post = postList[position] holder.postTitle.text = post.postTitle holder.postDescription.text = post.postDescription holder.postDate.text = post.postDate // 先清空ChipGroup残留的旧Chip,避免复用导致重复添加 holder.postTagsChipGroup.removeAllViews() // 遍历当前Post的标签列表生成对应Chip,若为单标签可直接创建无需遍历 post.tagList.forEach { tag -> val tagChip = Chip(holder.itemView.context).apply { id = View.generateViewId() text = tag // 可按需补充Chip样式、点击事件等配置 } holder.postTagsChipGroup.addView(tagChip) } }
内容的提问来源于stack exchange,提问作者Arshad Ali
相关产品推荐
相关产品推荐

