Search code examples
androidandroid-asynctaskandroid-recyclerview

RecyclerView: Async image-loading


Im using RecyclerView to display a list containing an imageView. To make the UI more fluently, I load 58dp thumbnails saved on sd card into these imageViews with an asyncTask.

The problem is, that once a childView comes in visual display, an old image from another data is being reused and then replaced once the AsyncTask finishes. I can stop the shuffling by setting the imageView bitmap to null in onPreExecute.

Is there a way to really reuse old images or do I really have to load the images from sd-card each time a new View comes in place? This makes view quite ugly because either there are wrong images first or the image is plain white.


Solution

  • Due to view reuse you'll fetch views with content already on them, this was a problem on ListViews too if you were using the ViewHolder pattern, which you should.

    There are two solutions here, the good practice and the bad hack:

    • In the good practice you set your ImageView to display nothing at the beginning of bindViewHolder(VH holder, int position) using setDrawable(null) or similar.

    • In the bad hack you wouldn't recycle/reuse views, not enforcing the ViewHolder pattern, and you'd inflate it every time, but that's only allowed in ListView and other old components.