【发布时间】:2017-03-23 04:37:52
【问题描述】:
像往常一样,我们使用适配器来填充 listView。在适配器中,我们使用 picasso 加载图像。我看到当将图像加载到目标(imageView)时,行被回收,毕加索将自动取消对该目标的请求。
离开片段或活动时如何取消所有未完成的请求?
【问题讨论】:
像往常一样,我们使用适配器来填充 listView。在适配器中,我们使用 picasso 加载图像。我看到当将图像加载到目标(imageView)时,行被回收,毕加索将自动取消对该目标的请求。
离开片段或活动时如何取消所有未完成的请求?
【问题讨论】:
这个答案可能来得有点晚,但也许有人仍然需要它......
定义一个提供清理方法的ViewHolder:
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 请求:
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) 将分离所有当前添加的Views,其关联的ViewHolders 将被回收。
【讨论】:
但前提是您不在列表/网格适配器中!请求图像 对于相同的图像视图/目标(例如,在适配器 getView 中)会做 这是自动的。你应该只需要取消(而且你不需要 实际上需要)如果您提出请求然后离开 屏幕。
【讨论】:
您也可以在片段/活动发出的请求上使用RequestCreator#tag(Object),然后使用Picasso#cancelTag(Object) 取消所有请求。
【讨论】: