startactivityforresult替代的例子
时间: 2023-09-03 20:15:05 浏览: 157
StartActivityForResult小例子
以下是使用startActivityForResult的替代示例:
1. 使用ActivityResultContracts.StartActivityForResult
在Kotlin中,可以使用ActivityResultContracts.StartActivityForResult来启动一个Activity并获取结果。例如:
```
class MyActivity : AppCompatActivity() {
private val startForResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val data = result.data
// 处理返回结果
}
}
fun launchActivityForResult() {
val intent = Intent(this, OtherActivity::class.java)
startForResult.launch(intent)
}
}
```
2. 自定义ActivityResultLauncher
在Java中,可以自定义ActivityResultLauncher来启动一个Activity并获取结果。例如:
```
public class MyActivity extends AppCompatActivity {
private ActivityResultLauncher<Intent> startForResult = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
// 处理返回结果
}
});
public void launchActivityForResult() {
Intent intent = new Intent(this, OtherActivity.class);
startForResult.launch(intent);
}
}
```
注意:以上两种方法都需要在Activity中调用registerForActivityResult()方法来注册ActivityResultLauncher。
阅读全文