RecyclerView滚动时item背景色变动 如何固定各item的随机头像背景色
你遇到的滑动后背景色变化是RecyclerView的item复用机制导致的。你当前的代码是每次item被绑定到界面(即onBindViewHolder执行)时都会调用随机方法生成新的背景,item被滑出屏幕后会被回收复用给新滑入的条目,每次复用都会重新执行随机逻辑,所以背景色会不断变化。
方案1:将背景资源ID存入数据实体类(推荐)
这种方案稳定性最高,即使列表有增删改操作也不会出现颜色错位问题。
- 给列表对应的实体类新增存储背景资源ID的字段,示例:
// 你的列表数据实体类 data class Client( // 原有字段保留,新增下面这个字段 val profileBgResId: Int )
- 第一次组装列表数据源时,就给每个条目生成固定的随机背景ID,仅生成一次:
val colorDrawables = arrayOf( R.drawable.client_list_background_color_drawable_1, R.drawable.client_list_background_color_drawable_2, R.drawable.client_list_background_color_drawable_3, R.drawable.client_list_background_color_drawable_4, R.drawable.client_list_background_color_drawable_5, R.drawable.client_list_background_color_drawable_6 ) // 原始数据转成带背景ID的列表数据 val finalClientList = rawClientList.map { it.copy(profileBgResId = colorDrawables[(Math.random() * 5).roundToInt()]) } // 将finalClientList传给Adapter
- 在Adapter的
onBindViewHolder中直接读取实体类的背景ID设置即可,不要再调用随机逻辑:
binding.clientHomeImageProfileColorBackground.background = ContextCompat.getDrawable(context, item.profileBgResId)
方案2:Adapter内缓存位置对应的背景ID(适合不想修改实体类的场景)
如果不方便修改实体类,可以在Adapter内部用缓存存储每个位置对应的背景ID,避免重复生成。
- 在Adapter内部定义缓存变量和背景资源数组:
// 用来缓存position对应的背景资源ID,SparseIntArray比HashMap更适合int类型的key private val bgResCache = SparseIntArray() private val colorDrawables = arrayOf( R.drawable.client_list_background_color_drawable_1, R.drawable.client_list_background_color_drawable_2, R.drawable.client_list_background_color_drawable_3, R.drawable.client_list_background_color_drawable_4, R.drawable.client_list_background_color_drawable_5, R.drawable.client_list_background_color_drawable_6 )
- 在
onBindViewHolder中优先读缓存,缓存不存在才生成新的随机背景并存入缓存:
val position = bindingAdapterPosition val bgRes = if (bgResCache.indexOfKey(position) >= 0) { bgResCache.get(position) } else { val randomRes = colorDrawables[(Math.random() * 5).roundToInt()] bgResCache.put(position, randomRes) randomRes } binding.clientHomeImageProfileColorBackground.background = ContextCompat.getDrawable(context, bgRes)
注意:如果你的列表有插入、删除、移动条目的操作,方案2需要同步更新缓存的key,否则会出现颜色错位,这种场景优先使用方案1。

内容的提问来源于stack exchange,提问作者codewithbawo
相关产品推荐
相关产品推荐

