[英]Android: Activity for result pressing back closes the app
In my app, I am opening a Contact activity to pick a contact using the new Activity Result API like this在我的应用程序中,我正在打开一个联系人活动来使用新的活动结果 API 来选择一个联系人,如下所示
registerForActivityResult(ActivityResultContracts.PickContact()) { it ->
viewModel.setContact(it)
}.launch(null)
The Contact activity opens, I can retrieve the contact, all this works just fine.联系人活动打开,我可以检索联系人,这一切都很好。 But while in the Contact activity, pressing the back button (either the android back button or the back arrow at the top), instead of closing just the contact activity, it exits my app.但是在 Contact 活动中,按下后退按钮(android 后退按钮或顶部的后退箭头),而不是仅关闭联系活动,它会退出我的应用程序。
I found fixes online for this issue, but only for the old startActivityForResult
and onActivityResult
APIs.我在网上找到了针对此问题的修复程序,但仅适用于旧的startActivityForResult
和onActivityResult
API。 Is there a way I can change the behavior of the back button when opening an activity for result for the new API as well?在为新 API 的结果打开活动时,有没有一种方法可以更改后退按钮的行为?
Edit: Noticed the behavior both on emulator and on physical device编辑:注意到模拟器和物理设备上的行为
Adrian kindly provided me with a sample of his project.阿德里安好心地向我提供了他的项目样本。 This answer is based on the results of debugging the sample project.此答案基于调试示例项目的结果。
There is one "invisible" issue in the code that is caused as the result of interoperability of Java and Kotlin languages.由于 Java 和 Kotlin 语言的互操作性,代码中存在一个“不可见”问题。 When we call Java function from Kotlin code we get return type of T!
当我们从 Kotlin 代码调用 Java 函数时,我们得到T!
返回类型T!
- where T!
- 哪里T!
means "T or T?".意思是“T 还是 T?”。
Java allows returning null
values as we wish. Java 允许按照我们的意愿返回null
值。 In order for Kotlin to know that the value is explicitly optional Java programmers must use @Nullable
annotation.为了让 Kotlin 知道该值是显式可选的,Java 程序员必须使用@Nullable
注释。 Kotlin will pick it up and return T?
Kotlin 会捡起来返回T?
instead.反而。
Since registerForActivityResult
is Java function we get in return, for registerForActivityResult(ActivityResultContracts.PickContact())
, result of type Uri!
由于registerForActivityResult
是我们返回的 Java 函数,对于registerForActivityResult(ActivityResultContracts.PickContact())
, Uri!
类型的结果Uri!
. .
Again, Uri!
又是Uri!
means "Uri or Uri?"意思是“乌里还是乌里?” - "value or null". - “值或空”。
To handle this value in a Kotlin style we can safely unwrap it by using question mark ?
要以 Kotlin 风格处理这个值,我们可以使用问号?
: :
activityResultLauncher = registerForActivityResult(ActivityResultContracts.PickContact()) {
it?.let { contactUri ->
viewModel.setContact(contactUri)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.