Tom*_*Tom 3 android onactivityresult
startActivityForResult(intent: Intent!, options: Bundle?)已被弃用。我正在尝试替换为,ActivityResultLauncher但我需要通过options. 我怎样才能用新方法做到这一点?以下是原始(现已弃用)方法的示例,该方法将打开“联系人”菜单,然后根据 的值在开关中执行以下两项操作之一code:
...
val code = contactType //can be either 1 or 2
val contactsIntent = Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI)
contactsIntent.type = ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE
startActivityForResult(contactsIntent, code)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if(resultCode == Activity.RESULT_OK) {
when(requestCode) {
1 -> { //Do something
}
2 -> { //Do something else
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我试图将上述内容转换为使用,ActivityResultLauncher但我还没有弄清楚如何将 的值传递code给它。以下是我到目前为止所拥有的:
val code = contactType //can be either 1 or 2
val contactsIntent = Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI)
contactsIntent.type = ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE
contactLauncher.launch(contactsIntent) //or maybe contactLauncher.launch(contactsIntent, code)?
private val contactLauncher: ActivityResultLauncher<Intent> = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if(it.resultCode == Activity.RESULT_OK) {
when(??? requestCode ???) {
1 -> { //Do something
}
2 -> { //Do something else
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您需要创建两个单独的 ActivityResultLauncher 对象,每个对象一个。
IMO,这正是谷歌试图解决的问题,有一个混乱的“onActivityResult”函数,以及必须处理 requestCodes。现在,这更类似于 OnClickListener 类型的回调。
他们对 Android 的其他部分也做了同样的事情,比如请求应用程序权限。requestCode 现在在内部处理。
| 归档时间: |
|
| 查看次数: |
991 次 |
| 最近记录: |