Strange behaviour of images in RecyclerView

后端 未结 3 1056
忘掉有多难
忘掉有多难 2020-12-23 09:52

I am using android.support.v7.widget.RecyclerView to show simple items containing text and in some cases also images. Basically I followed the tutorial from here https://dev

3条回答
  •  失恋的感觉
    2020-12-23 10:32

    Based on @Lion789's answer. I'm using Google's Volley for image and json loading.

    This allows us to retrieve the position on the view that's going to be recycled later.

    @Override
    public int getItemViewType(int position) {
        return position;
    }
    

    When making the request, set the position as the TAG

    @Override
    public void onBindViewHolder(final ItemHolder holder, int position) {
            ImageRequest thumbnailRequest = new ImageRequest(url,
                    new Response.Listener() {
                        @Override
                        public void onResponse(Bitmap response) {                          
                            holder.itemThumbnail.setImageBitmap(response);
                        }
                    },[...]);
    
            thumbnailRequest.setTag(String.valueOf(position)); //setting the TAG
            mQueue.addToRequestQueue(thumbnailRequest);
    }
    

    And when the view is being recycled we'll cancel the request, and remove the current image

    @Override
    public void onViewRecycled(ItemHolder holder) {
        super.onViewRecycled(holder);
        mQueue.cancelAll(String.valueOf(holder.getItemViewType()));
        holder.itemThumbnail.setImageDrawable(null);
    }
    

    Volley garanties that canceled requests won't be delivered.

提交回复
热议问题