首页 > 解决方案 > 如何在撰写中使用意图启动文件选择器

问题描述

我正在尝试在单击按钮时启动文件选择器(可组合功能)。无法使用startActivityForResult()

@Composable
fun SelectScreen() {

    Button(onClick = {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        startActivity(intent)
    }
    ) {
        Text("BUTTON")
    }
}

标签: androidkotlinandroid-jetpack-compose

解决方案


这是我的建议:

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

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

并在显示图像的可组合中,您可以执行以下操作

val image = remember {
   // Make sure to resize and compress
   // the image to avoid display a big bitmap
   ImageUtils.imageFromUri(imageUi)
}
Image(
   image,
   contentDescription = null
)

推荐阅读