简体   繁体   中英

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

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 .

     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

      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. This should work.

Note: If user selects a single photo then result.getData().getData() code will be executed. If user select multiple photos then result.getData().getClipData() code will be executed. So the if statement is important.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM