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")
}
}
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
)
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 {
//...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With