You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

上下滚动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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 07:15:02