glide和RecyclerView版本:
implementation 'com.github.bumptech.glide:glide:3.8.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
列表适配器代码
//未封装adapter
public class GridAdapterNoPack extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private LayoutInflater mLayoutInflater;
List<SearchResultItem> list;
public GridAdapterNoPack(Context context, List<SearchResultItem> list) {
mLayoutInflater = LayoutInflater.from(context);
this.list = list;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mLayoutInflater.inflate(R.layout.grid_item, parent, false);
ItemViewHolder viewHolder = new ItemViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
if (position < list.size()) {
ImageView iv = ((ItemViewHolder) holder).mContentTv;
Glide.with(iv.getContext())
.load(list.get(position).getPgrpLogo())
.placeholder(R.mipmap.epg_bg)
.listener(new RequestListener<String, GlideDrawable>() {
@Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
Log.e("Glide", " position:" + position + " onResourceReady");
return false;
}
})
.into(iv);
holder.itemView.setTag(position);
}
}
@Override
public int getItemCount() {
return this.list.size();
}
class ItemViewHolder extends RecyclerView.ViewHolder {
private ImageView mContentTv;
ItemViewHolder(View itemView) {
super(itemView);
mContentTv = itemView.findViewById(R.id.video_image);
}
}
void add(List<SearchResultItem> list, boolean b) {
this.list.addAll(list);
notifyDataSetChanged();
}
}
滑动列表 观察图片加载情况,onResourceReady打印了表示该位置图片加载完成。可得出结论:item不可见时线程及时回收了。
因为我在项目中使用了BaseQuickAdapter类,观察发现快速滑动,之前的item还是会加载。
为了解决这个问题,只得手动停止加载,代码如下:
@Override
public void onViewDetachedFromWindow(@NonNull RecyclerView.ViewHolder holder) {
super.onViewDetachedFromWindow(holder);
if(holder.getAdapterPosition()!=-1){
Glide.clear(holder.itemView.findViewById(R.id.video_image));
}
}
值得注意的是,我本来使用glide4.9.0时,无论有没有使用baseQuickAdapter都没办法暂停线程。所以回退到了3.8.0
新版本真的要慎重检验再使用。