[英]how I can select multiple images from gallery in android studio
This is my code:-这是我的代码:-
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
I tried using a set of libraries, but I could not add a limit that makes the user select a maximum of 10 images我尝试使用一组库,但无法添加使用户 select 最多 10 张图像的限制
Ok you need to understand a few things.好的,您需要了解一些事情。 Firstly, if you want to limit the number of items user can pick from intent don't use default method like you used.
首先,如果您想限制用户可以从意图中选择的项目数量,请不要像您使用的那样使用默认方法。 Instead create an activity then customize it.
而是创建一个活动然后对其进行自定义。 Secondly, If you want to use default system, let user select as much as user wants but take only those which you want from the ActivityResultLauncher .
其次,如果你想使用默认系统,让用户 select 尽可能多地使用,但只从ActivityResultLauncher中获取你想要的那些。
Intent intent = new Intent();
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
someActivityResultLauncher.launch(intent);
Use this above code in onClick method and在 onClick 方法中使用上面的代码和
ArrayList<Uri> files;
someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
if (null != result.getData()) {
files = new ArrayList<>();
if (null != result.getData().getClipData()) {
int count = result.getData().getClipData().getItemCount();
if (count >= 10) {
showSweetAlertError(this, "Error", "Maximum 10 photo.");
}
for (int i = 0; i < Math.min(count, 10); i++) {
Uri uri = result.getData().getClipData().getItemAt(i).getUri();
files.add(uri);
}
} else {
Uri uri = result.getData().getData();
files.add(uri);
}
}
}
});
Create ActivityResultLauncher<Intent> someActivityResultLauncher
globally then in onCreate write the above code.全局创建
ActivityResultLauncher<Intent> someActivityResultLauncher
然后在 onCreate 中编写上面的代码。 This should work.这应该工作。
Note: If user selects a single photo then result.getData().getData()
code will be executed.注意:如果用户选择单张照片,则将
result.getData().getData()
代码。 If user select multiple photos then result.getData().getClipData()
code will be executed.如果用户 select 多张照片然后
result.getData().getClipData()
代码将被执行。 So the if statement is important.所以if语句很重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.