I have a RecyclerView to display list data but after Scrolling up and down, a image load from url using Volley disappear and appear again. I know that the list will recycle item after read this How ListView's recycling mechanism works. Here is my Adapter, where did I wrong?
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
private ArrayList<Post> posts;
private Context context;
private ImageLoader imageLoader;
public PostAdapter(ArrayList<Post> posts, Context context) {
this.posts = posts;
this.context = context;
imageLoader = MySingleton.getInstance(context).getImageLoader();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_post, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.name.setText(posts.get(position).getName());
holder.timestamp.setText(posts.get(position).getTimestamp());
holder.status.setText(posts.get(position).getStatus());
holder.avatar.setImageUrl(Constants.URL_IMAGE + posts.get(position).getAvatar(), imageLoader);
if(!posts.get(position).getImage().equals("")) {
holder.image.setVisibility(View.VISIBLE);
holder.image.setImageUrl(Constants.URL_IMAGE + posts.get(position).getImage(), imageLoader);
} else {
holder.image.setVisibility(View.GONE);
}
}
@Override
public int getItemCount() {
return posts.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
NetworkImageView image, avatar;
TextView status, timestamp, name;
public ViewHolder(View itemView) {
super(itemView);
avatar = (NetworkImageView) itemView.findViewById(R.id.profilePic);
image = (NetworkImageView) itemView.findViewById(R.id.feedImage1);
status = (TextView) itemView.findViewById(R.id.txtStatusMsg);
name = (TextView) itemView.findViewById(R.id.name);
timestamp = (TextView) itemView.findViewById(R.id.timestamp);
}
}}
In your implementation you're calling
setImageUrl()
every time you bind to the view holder. EventhoughImageLoader
supports and uses a cache, it's on the networking level, giving you a short delay between setting the url and displaying the image (disappear and appear).To handle this better, you should implement an in-memory cache for your images and set these directly like
where
cache
would be your own implementation.do like this