首页 > 解决方案 > RecyclerView 项目在滚动时显示相同的背景颜色

问题描述

我是 android 新手,我的回收站视图有问题。我希望使用随机颜色作为个人资料图像背景,但是当我上下滑动几次时颜色会不断变化,我希望每个项目都保持特定的颜色。请问我怎样才能做到这一点。这是我为随机化颜色所做的:

private fun changeClientProfileBackgroundColor ():Drawable?{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 )return ContextCompat.getDrawable(
        context!!, colorDrawables[(Math.random() * 5).roundToInt()])}



binding.clientHomeImageProfileColorBackground.background =
                changeClientProfileBackgroundColor()

具有随机背景颜色的回收站视图的图像

标签: androidandroid-studiokotlinandroid-recyclerview

解决方案


如果您的适配器视图不稳定,请尝试在 recyclerview 适配器中使用getItemViewType 。

检查 stackoverflow 中的这个先前的问题以获取更多参考。

Recyclerview 在滚动期间更改项目


推荐阅读