0

I am new to android, and I am having an issue with my recycler view. I want to have a random color as the profile image background, but the color keeps changing when I swipe up and down some couple of times, I want each item to maintain a particular color. Please how can I achieve this. This is what I have done to randomize the colors:

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()

Image of the recycler view with the background random colors

2 Answers2

0

Try using getItemViewType in recyclerview adapter if your adapter view is not stable.

Check this previous question in stackoverflow for more reference.

Recyclerview Changing Items During Scroll

0

To set a random background color or img in each item, please follow this exemple. This exemple use background color but still same process if you want image.

@Override
   public void onBindViewHolder(MyViewHolder viewHolder, int i) {
      studentData data=studentDataList.get(i);
      Random rnd = new Random();
      int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
      viewHolder.parent.setBackgroundColor(currentColor);
      viewHolder.name.setText(data.name);
      viewHolder.age.setText(String.valueOf(data.age));
   }

This is what you excepted to have

This tutorial explain in details the procedure

stic-lab
  • 433
  • 7
  • 16