Jetpack Compose:从 Composable 函数启动 ActivityResultContract 请求 [英] Jetpack Compose: Launch ActivityResultContract request from Composable function
问题描述
截至 1.2.0-beta01androidx.activity:activity-ktx
,不能再launch
使用Activity.registerForActivityResult()
创建的请求,如上面链接中突出显示的在行为改变"下并在 此处的 Google 问题中看到.
As of 1.2.0-beta01 of androidx.activity:activity-ktx
, one can no longer launch
the request created using Activity.registerForActivityResult()
, as highlighted in the above link under "Behavior Changes" and seen in the Google issue here.
应用程序现在应该如何通过 @Composable
函数启动这个请求?以前,应用程序可以通过使用 Ambient
将 MainActivity
的实例沿链向下传递,然后轻松启动请求.
How should an application launch this request via a @Composable
function now? Previously, an app could pass the instance of the MainActivity
down the chain via using an Ambient
and then launch the request easily.
可以通过以下方式解决新行为,例如,在活动的 onCreate
函数之外实例化后,将注册活动结果的类传递到链中,然后在可组合
.但是,不能通过这种方式注册完成后执行的回调.
The new behavior can be worked around by, for example, passing a class registering for the activity result down the chain after being instantiated outside of the Activity's onCreate
function, and then launch the request in a Composable
. However, registering the a callback to be executed after completion cannot be done this way.
可以通过创建自定义 ActivityResultContract
来解决这个问题,它在启动时接受回调.但是,这意味着几乎没有任何内置 ActivityResultContracts
可以与 Jetpack Compose 一起使用.
One could get around this by creating custom ActivityResultContract
, which, at launch, take a callback. However, this would mean that virtually none of the built-in ActivityResultContracts
could be used with Jetpack Compose.
TL;DR
应用如何从 @Composable
函数启动 ActivityResultsContract
请求?
How would an app launch an ActivityResultsContract
request from a @Composable
function?
推荐答案
从 androidx.activity:activity-compose:1.3.0-alpha06
开始,registerForActivityResult()
API 已重命名为 rememberLauncherForActivityResult()
以更好地表明返回的 ActivityResultLauncher
是代表您记住的托管对象.
As of androidx.activity:activity-compose:1.3.0-alpha06
, the registerForActivityResult()
API has been renamed to rememberLauncherForActivityResult()
to better indicate the returned ActivityResultLauncher
is a managed object that is remembered on your behalf.
val result = remember { mutableStateOf<Bitmap?>(null) }
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.TakePicturePreview()) {
result.value = it
}
Button(onClick = { launcher.launch() }) {
Text(text = "Take a picture")
}
result.value?.let { image ->
Image(image.asImageBitmap(), null, modifier = Modifier.fillMaxWidth())
}
这篇关于Jetpack Compose:从 Composable 函数启动 ActivityResultContract 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!