Ukubu
Ukubu

Reputation: 820

RecyclerView uses wrong values

So, I use a RecyclerView for displaying a grid. In the onBindViewHolder method of its adapter I update the view content. I put a part of the update into another thread to keep the UI alive.

@Override
public void onBindViewHolder (final MovieHolder holder, final int position) {
    // Blah, blah. Set movie details. Everything is fine.

    // Generate a palette or load from the memory and adjust the background color of the view.
     new Thread(new Runnable() {
        @Override
        public void run () {
            Palette palette = getPalette();
            final Palette.Swatch bestSwatch = findBestSwatch(palette)                

            if (bestSwatch != null) {
                activity.runOnUiThread(new Runnable(
                   @Override
                   public void run() {
                       holder.layout.setBackgroundColor(bestSwatch.getRgb());
                   }
                ));
            }
        }
    }).start();
}

It works well, except when no bestSwatch was found. Then for the first time, it displays a correct background color and when I scroll down and back it will have a random color from one of the views.

Why does RecyclerView changes the color of my view when I don't update it?

Upvotes: 0

Views: 549

Answers (1)

Elvis Chweya
Elvis Chweya

Reputation: 1530

RecyclerView reuses its rows, the ViewHolders, hence its name. So your problem is that a recycled view has the background color it was set to at another recent position. Solution to this is simple...

Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
        @Override
        public void onGenerated(Palette palette) {

            Palette.Swatch swatch = palette.getDarkVibrantSwatch();

            if (swatch == null)
                swatch = new Palette.Swatch(ContextCompat.getColor(context, R.color.fallback_background), 4);

            holder.layout.setBackgroundColor(swatch.getRgb());
        }
    });

So, you always set a BackgroundColor. When there's no swatch generated, you create one using a fallback layout background color you define at colors.xml

Upvotes: 1

Related Questions