如何解决Jetpack撰写:从Composable函数启动ActivityResultContract请求
自androidx.activity:activity-ktx
的{{3}}起,不再可以launch
使用Activity.registerForActivityResult()
创建的请求,如上面链接“行为更改”下突出显示的内容所示。 1.2.0-beta01。
应用程序现在应该如何通过@Composable
函数启动此请求?以前,应用程序可以通过使用MainActivity
将Ambient
的实例沿链向下传递,然后轻松启动请求。
可以通过以下方法来解决新行为:例如,在Activity的onCreate
函数之外实例化实例之后,将注册活动结果的类向下传递给链,然后在{{1 }}。但是,无法以这种方式注册要在完成后执行的回调。
可以通过创建自定义Composable
来解决此问题,该自定义ActivityResultContract
在启动时会进行回调。但是,这实际上意味着内置ActivityResultContracts
都不能与Jetpack Compose一起使用。
TL; DR
应用如何通过ActivityResultsContract
函数启动@Composable
请求?
解决方法
自 androidx.activity:activity-compose:1.3.0-alpha06
起,registerForActivityResult()
API 已重命名为 rememberLauncherForActivityResult()
,以更好地表明返回的 ActivityResultLauncher
是代表您记住的托管对象。>
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())
}
,
自 Activity Compose 1.3.0-alpha03
及以后,有一个新的效用函数 registerForActivityResult()
可以简化此过程。
@Composable
fun RegisterForActivityResult() {
val result = remember { mutableStateOf<Bitmap?>(null) }
val launcher = registerForActivityResult(ActivityResultContracts.TakePicturePreview()) {
result.value = it
}
Button(onClick = { launcher.launch() }) {
Text(text = "Take a picture")
}
result.value?.let { image ->
Image(image.asImageBitmap(),modifier = Modifier.fillMaxWidth())
}
}
(来自给定的样本 here )
,活动结果具有两个API界面:
- 核心
ActivityResultRegistry
。这实际上是基础工作。 -
ActivityResultCaller
中的便捷界面,其中实现了ComponentActivity
和Fragment
,将Activity Result请求与Activity或Fragment的生命周期相关联
一个Composable的生存期与Activity或Fragment的生存期不同(例如,如果您从层次结构中删除Composable,则它应该在其自身之后进行清理),因此使用ActivityResultCaller
API,例如registerForActivityResult()
永远都不是正确的事情。
相反,您应该直接使用ActivityResultRegistry
API,直接调用register()
和unregister()
。最好与rememberUpdatedState()
和DisposableEffect
配对,以创建可与Composable配合使用的registerForActivityResult
版本:
@Composable
fun <I,O> registerForActivityResult(
contract: ActivityResultContract<I,O>,onResult: (O) -> Unit
) : ActivityResultLauncher<I> {
// First,find the ActivityResultRegistry by casting the Context
// (which is actually a ComponentActivity) to ActivityResultRegistryOwner
val owner = ContextAmbient.current as ActivityResultRegistryOwner
val activityResultRegistry = owner.activityResultRegistry
// Keep track of the current onResult listener
val currentOnResult = rememberUpdatedState(onResult)
// It doesn't really matter what the key is,just that it is unique
// and consistent across configuration changes
val key = rememberSavedInstanceState { UUID.randomUUID().toString() }
// Since we don't have a reference to the real ActivityResultLauncher
// until we register(),we build a layer of indirection so we can
// immediately return an ActivityResultLauncher
// (this is the same approach that Fragment.registerForActivityResult uses)
val realLauncher = mutableStateOf<ActivityResultLauncher<I>?>(null)
val returnedLauncher = remember {
object : ActivityResultLauncher<I>() {
override fun launch(input: I,options: ActivityOptionsCompat?) {
realLauncher.value?.launch(input,options)
}
override fun unregister() {
realLauncher.value?.unregister()
}
override fun getContract() = contract
}
}
// DisposableEffect ensures that we only register once
// and that we unregister when the composable is disposed
DisposableEffect(activityResultRegistry,key,contract) {
realLauncher.value = activityResultRegistry.register(key,contract) {
currentOnResult.value(it)
}
onDispose {
realLauncher.value?.unregister()
}
}
return returnedLauncher
}
然后可以通过以下代码在自己的Composable中使用它:
val result = remember { mutableStateOf<Bitmap?>(null) }
val launcher = registerForActivityResult(ActivityResultContracts.TakePicturePreview()) {
// Here we just update the state,but you could imagine
// pre-processing the result,or updating a MutableSharedFlow that
// your composable collects
result.value = it
}
// Now your onClick listener can call launch()
Button(onClick = { launcher.launch() } ) {
Text(text = "Take a picture")
}
// And you can use the result once it becomes available
result.value?.let { image ->
Image(image.asImageAsset(),modifier = Modifier.fillMaxWidth())
}
,
对于那些在我的案例中没有使用@ianhanniballake提供的要点取回结果的人,returnedLauncher
实际上捕获了realLauncher
的已处置值。
因此,尽管删除间接层应该可以解决此问题,但这绝对不是实现此目的的最佳方法。
这是更新的版本,直到找到更好的解决方案为止:
@Composable
fun <I,onResult: (O) -> Unit
): ActivityResultLauncher<I> {
// First,find the ActivityResultRegistry by casting the Context
// (which is actually a ComponentActivity) to ActivityResultRegistryOwner
val owner = AmbientContext.current as ActivityResultRegistryOwner
val activityResultRegistry = owner.activityResultRegistry
// Keep track of the current onResult listener
val currentOnResult = rememberUpdatedState(onResult)
// It doesn't really matter what the key is,just that it is unique
// and consistent across configuration changes
val key = rememberSavedInstanceState { UUID.randomUUID().toString() }
// TODO a working layer of indirection would be great
val realLauncher = remember<ActivityResultLauncher<I>> {
activityResultRegistry.register(key,contract) {
currentOnResult.value(it)
}
}
onDispose {
realLauncher.unregister()
}
return realLauncher
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。