毕加索:如何取消适配器中发出的所有图像请求 [英] picasso: how to cancel all image requests made in an adapter

查看:60
本文介绍了毕加索:如何取消适配器中发出的所有图像请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像往常一样,我们使用适配器来填充列表视图.在适配器中,我们使用 picasso 加载图像.我看到当将图像加载到目标 (imageView) 时,由于行被回收,毕加索将自动取消对该目标的请求.

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 (imageView) picasso will automatically cancel requests for that target.

如何在离开片段或活动时取消所有未完成的请求?

how does one cancel all of the outstanding requests when leaving the fragment or activity?

推荐答案

这个答案可能来得有点晚,但也许有人仍然需要它...

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

定义一个ViewHolder,它提供了一个清理方法:

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);
    }
}

在你的适配器中实现onViewRecycled():

static class ImageAdapter extends RecyclerView.Adapter<ImageHolder> {

    // ...

    @Override
    public void onViewRecycled(final ImageHolder holder) {
        holder.cleanup();
    }
}

当您的 Fragment 视图被销毁时(或您希望时)取消 Picasso 请求:

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) 将分离所有当前添加的 View 并且它们关联的 ViewHolder 将被回收.

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

这篇关于毕加索:如何取消适配器中发出的所有图像请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆