private val childFragmentResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
when (result.resultCode) {
Activity.RESULT_OK -> {
val data = result.data
// 处理结果
}
else -> {
//处理结果异常的情况
}
}
}
private fun launchChildFragment(requestCode: String) {
val intent = Intent(requireContext(), ChildFragment::class.java)
childFragmentResult.launch(intent.apply {
putExtra("request_code", requestCode)
})
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val requestCode = data?.getStringExtra("request_code")
// 处理结果并将其返回给父Fragment
parentFragmentManager.setFragmentResult(requestCode, bundleOf("result_key" to result))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//监听使用的关键字以接收结果
parentFragmentManager.setFragmentResultListener("request_code_one", this) { _, result ->
// 处理结果
}
parentFragmentManager.setFragmentResultListener("request_code_two", this) { _, result ->
// 处理结果
}
}
override fun onFragmentResult(requestKey: String, result: Bundle) {
//在这里处理结果
}
通过使用这种方法,可以轻松地从子Fragment中共享结果,并通过使用唯一的请求代码来将结果与父Fragment中源自的不同请求区分开来。