Aditya Nandardhane
Aditya Nandardhane

Reputation: 1413

How to set maximum Image selection limit while pickup image from Gallery in Jetpack compose

I have implemented multiple image selections from the gallery. However, I want to limit the user to select max 5 images from the gallery.

  TextButton(onClick = {
            scope.launch {
                uploadImageLauncher.launch("image/*")
            }
        }

Upvotes: 1

Views: 2757

Answers (4)

Siddhesh Shirodkar
Siddhesh Shirodkar

Reputation: 901

Create launcher with maxitems set :

private var imagePickerLauncher =
    registerForActivityResult(ActivityResultContracts.PickMultipleVisualMedia(maxItems = 5)) { resultUris ->
        resultUris.forEach { uri ->
            val file = FileUtils.getFile(requireContext(), uri)
            Toast.makeText(requireContext(), "new data : $file", Toast.LENGTH_SHORT).show()
        }
    }

Then launch using PickVisualMediaRequest

val request: PickVisualMediaRequest = PickVisualMediaRequest.Builder()
                .setMediaType(ImageOnly)
                .build()
            imagePickerLauncher.launch(request)

NOTE : FileUtils class gets file name from URI : https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java

For using photo picker in JETPACK COMPOSE refer to this video Photo picker using Compose

Upvotes: 0

Vahit Keskin
Vahit Keskin

Reputation: 438

When you set "maxItems", you cannot go beyond this number.

val multiplePhotoPickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.PickMultipleVisualMedia(maxItems = 10),
        onResult = { uris -> selectedImageUris = uris }
    )

It worked for me.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1007474

You have not specified what launcher is.

If you use the new PickMultipleVisualMedia launcher, you can specify maxItems to attempt to limit the number of selections. However, that request will not be honored on all devices, and you will need to check your results to see how many items you get back.

Upvotes: 5

Robert S
Robert S

Reputation: 846

Unfortunately, applying limit to gallery images selection is not possible via inbuild methods. You have to apply some condition is your code, like below:

if(imagesArraylist.size() == 10) {
      Log.e("Show pop-up OR toast msg ", "that you have exceeded selection limit");
} else {
// do something relevant to handle else condition
}

Assuming imagesArraylist is where you are adding the images URI which are selected from gallery.

Upvotes: 2

Related Questions