我正在使用 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);
}
}
}
未加载新图像时,回收器会显示以前的项目。 那么如何解决这个问题呢?
最佳答案
终于找到解决办法了。只需在 Adapter 类中添加以下代码即可:
@Override
public long getItemId(int position) {
return (long) (position);
}
@Override
public int getItemViewType(int position) {
return position;
}
关于java - 当我使用 ion 库加载图像时 RecyclerView 元素重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57796680/