Reputation: 600
I have a RecyclerView
and each item of RecyclerView
is having ImageView
. I am loading the image in that ImageView
using Glide
. I saw some blog says Glide
can load image asynchronously but I can not see this from the code below. It seems it only load one image when onBindViewHolder
is invoked. How does it show asynchrony?
public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.ViewHolder> {
private Context mContext;
private List<GalleryItem> mList;
public GalleryAdapter(Context mContext, List<GalleryItem> mList) {
this.mContext = mContext;
this.mList = mList;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public ViewHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.gallery_item);
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_gallery,
parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
GalleryItem item = mList.get(position);
holder.mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
Glide.with(mContext)
.load(item.getUrl())
.thumbnail(0.5f)
.into(holder.mImageView);
}
@Override
public int getItemCount() {
return mList.size();
}
public void addAll(List<GalleryItem> newList) {
mList.addAll(newList);
}
public void clear() {
mList.clear();
}
}
Upvotes: 6
Views: 14018
Reputation: 2066
The load method does it's work asynchronously when you load images to ImageView take a look on these threads:
In the third thread it's mentioning how to make "SYNCHRONOUS" load for an image to be used in a background thread meaning that it's by default made asynchronously
Bitmap myBitmap = Glide.with(applicationContext)
.load(yourUrl)
.asBitmap()
.centerCrop()
.into(500, 500)
.get()
and it's saying also this call above CAN"T be done on main thread but they did not mention any of that when they were talking about the normal loading into an imageView which is also an evidence that the normal load is made async then automatically after loading it moves the result to main thread to be used by method into(imageView).
I really tried to find it explicit but could not find it anywhere in docs so I thought it's obvious because they did not tell us to manage the background threading like in the mentioned case above.
Upvotes: 0
Reputation: 1739
According to glide documentation here and here you should use the into() method that returns FutureTarget and not the one that returns a Target. This method take width and height, not an ImageView : "If you actually want to interact with a decoded image on a background thread, instead of using downloadOnly you can use the version of into() that returns a FutureTarget."
Upvotes: 2