Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I start file chooser using intent in compose

I am trying to start file chooser on a button click (composable function). Unable to use startActivityForResult().

@Composable
fun SelectScreen() {

    Button(onClick = {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        startActivity(intent)
    }
    ) {
        Text("BUTTON")
    }
}
like image 977
Hitesh Patel Avatar asked Feb 17 '26 12:02

Hitesh Patel


2 Answers

Here is my suggestion:

val pickPictureLauncher = rememberLauncherForActivityResult(
    ActivityResultContracts.GetContent()
) { imageUri ->
    if (imageUri != null) {
        // Update the state with the Uri
    }
}

// In your button's click
pickPictureLauncher.launch("image/*")

and in your composable which display the image, you can do the following

val image = remember {
   // Make sure to resize and compress
   // the image to avoid display a big bitmap
   ImageUtils.imageFromUri(imageUi)
}
Image(
   image,
   contentDescription = null
)
like image 60
nglauber Avatar answered Feb 19 '26 03:02

nglauber


You can use rememberLauncherForActivityResult() to register a request to Activity#startActivityForResult, designated by the given ActivityResultContract.

This creates a record in the ActivityResultRegistry associated with this caller, managing request code, as well as conversions to/from Intent under the hood.

Something like:

val result = remember { mutableStateOf<Uri?>(null) }
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) {
    result.value = it
}

Button(onClick = { launcher.launch(arrayOf("image/*")) }) {
    Text(text = "Open Document")
}

result.value?.let {
   //...
}
like image 24
Gabriele Mariotti Avatar answered Feb 19 '26 03:02

Gabriele Mariotti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!