RecyclerView lazy loading

放肆的年华 提交于 2020-01-15 12:15:57

问题


I'm doing lazy loading on a RecyclerView adapter. First I fetch the image metadata (if it has any) and then let Picasso download the actual image.

public class PostHolder extends RecyclerView.ViewHolder implements Callback<Photo>{
    private PostImageView cover;
    private TextView content;
    private long id;

    public PostHolder(View itemView) {
        super(itemView);
        this.itemView.setOnClickListener(onClickListener);
        content = (TextView) itemView.findViewById(R.id.post_content);
        cover = (PostImageView) itemView.findViewById(R.id.post_image);
    }

    public void setPost(final Post post, int i){
        cover.unsetImage();
        this.id = post.getPhotoId();
        itemView.setTag(i);
        content.setText(post.getMessage());

        if("photo".equals(post.getType()) || "video".equals(post.getType()) && id != 0L){
            cache.get(id, this);
        }else{
            cover.setUrl(post.getImageUrl());
        }
    }

    @Override
    public void result(Photo result) {
        if(result != null && result.getId() == PostHolder.this.id){
            cover.setPhoto(result);
        }
    }
}

cache.get() loads my metadata from the cache, the result is returned with result().setPost() gets called in onBindViewHolder(). Now I'm getting everyone's favorite viewholder issue - my ImageView displays a different image before switching to the correct one. I know that Picasso correctly handles this and I have a check for my own loading where i compare the holder's id to the metadata id. I've spent a few hours on this already. Internet, you are my only hope.


回答1:


It's fixed now, though I'm not exactly sure why. I believe it's

Picasso
    .with(getContext())
    .cancelRequest(this);

inside unsetImage() because of the double request needed to load it.

What I think happens:

  1. Picasso is still loading the previous image.
  2. A call for the current image metadata is dispatched.
  3. Picasso loads the preVious image. Since Picasso doesn't know about the metadata, it's not automatically canceled.
  4. The metadata get's loaded, and Picasso starts loading the current image.


来源:https://stackoverflow.com/questions/27460779/recyclerview-lazy-loading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!