下面是获取图库图片并在recycler适配器中显示它们的示例代码:
1.在AndroidManifest.xml文件中包含以下权限:
2.创建一个方法来获取图库中的所有图像:
private ArrayList
String[] projection = new String[]{
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.DATE_ADDED,
MediaStore.Images.Media.DATA
};
Cursor cursor = getContentResolver().query(collection, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
int imageId = Integer.parseInt(cursor.getString(cursor.getColumnIndex(projection[0])));
Uri imageUri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + imageId);
imagesList.add(imageUri);
} while (cursor.moveToNext());
cursor.close();
}
return imagesList;
}
3.通过以下代码将Uri转化为Bitmap:
private Bitmap uriToBitmap(Uri uri) throws IOException { return MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri); }
4.将上述方法放在RecyclerView适配器的构造函数中,以便可以立即获取图像并在列表中显示它们:
public ImageAdapter(Context context) { this.context = context; this.images = getAllImages(); }
5.我们现在需要在ViewHolder类中设置ImageView,以便将图像显示在它们的位置上。在bind()方法中添加以下代码:
private ImageView imageView;
public ImageViewHolder(View view) { super(view); imageView = view.findViewById(R.id.image); }
public void bind(Uri imageUri) {
try {
Bitmap bitmap = uriToBitmap(imageUri);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
6.现在,RecyclerView适配器完整的代码应该如下所示:
public class ImageAdapter extends RecyclerView