简体   繁体   English

JetpackCompose 如何创建Chooser 并监听结果

[英]JetpackCompose how to createChooser and listen for result

I want to show a system dialog to user to select from available applications for sharing text from my app.我想向用户显示一个系统对话框,以便从可用的应用程序中进行选择,以便从我的应用程序中共享文本。 I can do this by using createChooser function from Intent class.我可以通过使用 Intent 类中的 createChooser 函数来做到这一点。 But i also want to listen for the system dialog result, so that i can disable/enable my share button to prevent creating multiple system dialogs overlapping each other.但我也想听系统对话框的结果,这样我就可以禁用/启用我的共享按钮,以防止创建多个系统对话框相互重叠。

To do this i need to know whenever the dialog is dismissed or an app option is selected by the user.为此,我需要知道何时关闭对话框或用户选择了应用程序选项。 So i need the result of the chooser Dialog i have created.所以我需要我创建的选择器对话框的结果。

I was able to get the selected app, but was not able to listen the dismiss event for the system dialog because Intent.ACTION_CLOSE_SYSTEM_DIALOGS event is deprecated for third party applications.我能够获取选定的应用程序,但无法监听系统对话框的关闭事件,因为第三方应用程序不推荐使用Intent.ACTION_CLOSE_SYSTEM_DIALOGS事件。 So is there any other way on how to know when the system dialog is closed?那么有没有其他方法可以知道系统对话框何时关闭?

Thanks in advance.提前致谢。

I was able to listen the result using rememberLauncherForActivityResult Composable function by combining it with ActivityResultContracts.StartActivityForResult abstract class.通过将它与ActivityResultContracts.StartActivityForResult抽象类结合使用,我能够使用rememberLauncherForActivityResult组合函数来收听结果。 you can see the usage example i have implemented below.你可以看到我在下面实现的使用示例。 Please share your opinions/corrections or alternatives for my problem.请分享您对我的问题的意见/更正或替代方案。

var shareEnabled by remember { mutableStateOf(true) }
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        // you can use the ActivityResult(it) here
        shareEnabled = true
    }
Button(
    onClick = {
        shareEnabled = false
        launcher.launch(getShareText().shareExternal())
    },
    enabled = shareEnabled
)

shareExternal is an extension function that creates and returns the chooser Intent; shareExternal 是一个扩展函数,它创建并返回选择器 Intent;

fun String.shareExternal(): Intent {
    val dataToShare = this
    val sendIntent: Intent = Intent().apply {
        action = Intent.ACTION_SEND
        putExtra(Intent.EXTRA_TEXT, dataToShare)
        type = "text/plain"
    }
    return Intent.createChooser(sendIntent, null)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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