picasso: how to cancel all image requests made in an adapter

前端 未结 3 1992
情歌与酒
情歌与酒 2021-02-13 20:02

as usual we use an adapter to populate a listView. in the adapter we use picasso to load the images. i see that as rows are recycled when loading an image into an target (imageV

相关标签:
3条回答
  • 2021-02-13 20:55

    But only if you are not in a list/grid adapter! Requesting an image for the same imageview/target (e.g., in an adapter getView) will do this automatically. You should only need to cancel (and you don't actually need to) if you're making requests and then leaving the screen.

    https://github.com/square/picasso/issues/83

    0 讨论(0)
  • 2021-02-13 21:05

    This answer may come a bit late, but maybe someone still needs it...

    Define a ViewHolder which provides a cleanup method:

    static class ImageHolder extends RecyclerView.ViewHolder {
        public final ImageView image;
    
        public ImageHolder(final View itemView) {
            super(itemView);
            image = (ImageView) itemView.findViewById(R.id.image);
        }
    
        public void cleanup() {
            Picasso.with(image.getContext())
                .cancelRequest(image);
            image.setImageDrawable(null);
        }
    }
    

    Implement onViewRecycled() in your adapter:

    static class ImageAdapter extends RecyclerView.Adapter<ImageHolder> {
    
        // ...
    
        @Override
        public void onViewRecycled(final ImageHolder holder) {
            holder.cleanup();
        }
    }
    

    Cancel the Picasso requests when your Fragment's view is destroyed (or whenever you wish):

    public class MyFragment extends Fragment {
        private RecyclerView recycler;
    
        // ...
    
        @Override
        public void onDestroyView() {
            super.onDestroyView();
            recycler.setAdapter(null); // will trigger the recycling in the adapter
        }
    }
    

    RecyclerView.setAdapter(null) will detach all currently added Views and their associated ViewHolders will be recycled.

    0 讨论(0)
  • 2021-02-13 21:07

    You can also use RequestCreator#tag(Object) on the requests made by your fragment/activity, then use Picasso#cancelTag(Object) to cancel all of them.

    0 讨论(0)
提交回复
热议问题