Search code examples
androidgridviewpalette

Palette library changing colors while scrolling in GridView


I've been having some problems implementing the new Palette library (on 4.4.4 with 'com.android.support:palette-v7:21.0.+'). I am trying to color a part of each item in a GridView which works fine but when I scroll an item off the screen then back on it changes to a wrong color for a few moments before it goes back to the right color.

I thought the issue might have been calling view.setBackgroundColor every time getView was called, so I made a check before my code if it had already had a color generated. This made it even worse. Each time I scrolled around colors would swap With enough scrolling all my colors have swapped places. It seems like the colors are switching with each other too, not random.

Heres a snippet of what my code looks like:

Palette.generateAsync(bitmap,
    new Palette.PaletteAsyncListener() {
        @Override
        public void onGenerated(Palette palette) {
            Palette.Swatch vibrant =
                    palette.getMutedSwatch();
            if (vibrant != null) {
                fView.findViewById(R.id.colored_bar).setBackgroundColor(
                        vibrant.getRgb());
            }
        }
    });

Does anyone know a way to work around this problem? I heard mention of caching the response from Palette but wasn't sure if that would mean doing any more than I already am. I also tried both synchronous and asynchronous uses of Palette. Thanks.


Solution

  • I found the solution to this. Basically the problem was that the palette object was created every time, which was both costly and inaccurate. Since the palette is static, I created a ViewHolder and stored the palette in that once it was created.