首页 > 解决方案 > 当我使用离子库加载图像时,RecyclerView 元素重复

问题描述

我正在使用 ion 库在 recyclerview 中加载图像。但我面临一个问题。RecyclerView 正在重复项目。当图像未加载到新项目中时,它会显示以前加载的图像。如果未加载图像,我需要显示 ProgressBar。如何实现这一点。

这是我的适配器类:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

private String[] links;
private Context context;
private int screen_width;

public RecyclerViewAdapter(Context context, String[] links, int screen_width) {
    this.links = links;
    this.context = context;
    this.screen_width = screen_width;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(context).inflate(R.layout.list_item,viewGroup,false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int i) {
    loadImage(i, viewHolder);
}

private void loadImage(final int pos, final ViewHolder holder) {

    Ion.with(context)
            .load(links[pos])
            .withBitmap()
            .placeholder(R.drawable.icon_download_active)
            .error(R.drawable.icon_could_not_download)
            .fadeIn(true)
            .asBitmap()
            .setCallback(new FutureCallback<Bitmap>() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onCompleted(Exception e, Bitmap result) {
                    if ( e != null ) {
                        Log.i("IMAGE_LOADER_EV","Failed to load image \n Error:"+e.toString());
                    } else {
                        int h = (screen_width * result.getHeight()) / result.getWidth();
                        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(screen_width,h);
                        params.setMargins(0,0,0,dpToPx(context));

                        holder.image.setLayoutParams(params);
                        holder.image.setImageBitmap(result);
                    }
                }
            });

}

private static int dpToPx(Context context) {
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) 5, context.getResources().getDisplayMetrics());
}

@Override
public int getItemCount() {
    return links.length;
}

class ViewHolder extends RecyclerView.ViewHolder {
    ImageView image;
    TextView dimens;
    ProgressBar progressBar;
    ViewHolder(View view) {
        super(view);
        image = view.findViewById(R.id.image);
        dimens = view.findViewById(R.id.dimens);
        progressBar = view.findViewById(R.id.progress_bar);
    }
}

}

Recycler 在未加载新图像时显示以前的项目。那么如何解决这个问题呢?

标签: javaandroidandroid-recyclerviewandroid-ion

解决方案


利用:

Ion.with(imageView)

然后删除回调中ImageView中手动设置图像的位置。

.setCallback(...)

由于您使用回调来管理填充 ImageView,因此您正在创建一个竞争条件,其中 ImageView 在回收时由多个不同的项目加载。

使用 Ion.with(imageView) 允许 Ion 跟踪 RecyclerView 中的 ImageViews 并在 ImageViews 被回收时取消图像加载。

见样本:

https://github.com/koush/ion#load-an-image-into-an-imageview


推荐阅读