如何在RecyclerView中显示多张图像?

问题描述 投票:0回答:2

我正在尝试在android studio中开发图库应用,并且我正在使用RecyclerView布局有效地加载屏幕上的图像,但是每当我向下滚动时,应用都会崩溃一些图像。我得到的错误是java.lang.OutOfMemoryError,所以我认为我在类适配器上犯了一个错误,但找不到任何错误(我按照android文档Create a List with RecyclerView 中给出的步骤进行操作)。我尝试显示每个图像的缩略图,而不是实际图像,但是向下滚动几张图像后,应用程序崩溃了,我得到了[[该应用程序可能在其主线程上进行了太多工作错误

我将保留适配器类的代码。如果您需要更多代码示例或更多信息,请告诉我!

Pd:对不起,我不清楚,我的英语水平很差,我没有在这里问问题的经验,而且这是我在Android中的第一个应用程序。

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { public class ViewHolder extends RecyclerView.ViewHolder { public ImageView image; public ViewHolder(@NonNull View itemView) { super(itemView); image = (ImageView) itemView.findViewById(R.id.IMAGEN); } } private ArrayList<File> images = new ArrayList<>(); private Activity activity; public MyAdapter(ArrayList<File> images, Activity activity){ this.images.addAll(images); this.activity = activity; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { View v = activity.getLayoutInflater().inflate(R.layout.image_item, viewGroup, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { //Bitmap myBitmap = BitmapFactory.decodeFile(images.get(position).getAbsolutePath()); final int THUMBSIZE = 64; Bitmap ThumbImage = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(images.get(position).getAbsolutePath()), THUMBSIZE, THUMBSIZE); holder.image.setImageBitmap(ThumbImage); } @Override public int getItemCount() { return images.size(); }

java android android-recyclerview android-imageview android-constraintlayout
2个回答
0
投票
您可以使用Glide。如果您不想要,可以在onViewRecycled中清理图像像之类的东西

override fun onViewRecycled(holder: RecyclerView.ViewHolder) { super.onViewRecycled(holder) holder.image.setImageBitmap(null) }


0
投票
您可以使用Glide库在回收者视图中更有效地上传图像。另外,请尝试首先压缩位图,然后在图像视图中进行设置。通过压缩图像,OutOfMemory异常将得到解决]

摘自某人的StackOverflow答案。现在不记得链接了>

`public Bitmap compressInputImage(Uri inputImageData) { try { bitmapInputImage = MediaStore.Images.Media.getBitmap(context.getContentResolver(), inputImageData); if (bitmapInputImage.getWidth() > 2048 && bitmapInputImage.getHeight() > 2048) { dpBitmap = Bitmap.createScaledBitmap(bitmapInputImage, 1024, 1280, true); } else if (bitmapInputImage.getWidth() > 2048 && bitmapInputImage.getHeight() < 2048) { dpBitmap = Bitmap.createScaledBitmap(bitmapInputImage, 1920, 1200, true); } else if (bitmapInputImage.getWidth() < 2048 && bitmapInputImage.getHeight() > 2048) { dpBitmap = Bitmap.createScaledBitmap(bitmapInputImage, 1024, 1280, true); } else if (bitmapInputImage.getWidth() < 2048 && bitmapInputImage.getHeight() < 2048) { dpBitmap = Bitmap.createScaledBitmap(bitmapInputImage, bitmapInputImage.getWidth(), bitmapInputImage.getHeight(), true); } } catch (Exception e) { dpBitmap = bitmapInputImage; } return dpBitmap; }

© www.soinside.com 2019 - 2024. All rights reserved.