startactivityforresult方法被弃用,有其他的方法可以代替吗?具体怎么写代码
时间: 2024-05-02 20:17:43 浏览: 86
Android编程实现自动检测版本及自动升级的方法
是的,startActivityForResult方法已经被弃用,可以使用registerForActivityResult方法代替。具体代码如下:
在Activity中:
```
private val someActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
// 处理返回结果
val data: Intent? = result.data
}
}
val intent = Intent(this, SomeActivity::class.java)
someActivityResultLauncher.launch(intent)
```
在Fragment中:
```
private val someActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
// 处理返回结果
val data: Intent? = result.data
}
}
val intent = Intent(requireContext(), SomeActivity::class.java)
someActivityResultLauncher.launch(intent)
```
注意:需要使用kotlin时,需要在gradle中添加如下依赖:
```
implementation 'androidx.activity:activity-ktx:1.2.2'
implementation 'androidx.fragment:fragment-ktx:1.3.2'
```
阅读全文