Android Jetpack 导航库和 onActivityResult
Android Jetpack Navigation library and onActivityResult
我正在尝试将应用程序迁移到在 GoogleIO'18
上宣布的新 Navigation Architecture Component
假设我需要使用通常以 startActivityForResult
开头的 activity。这个activity来自图书馆或系统activity,所以我无法修改它。
有什么方法可以将此 activity 作为目的地包含在导航图中并从中获取结果吗?
到目前为止,我唯一的解决方案是将 activity 包裹在捕获结果的片段后面,然后将其呈现给导航图:
class ScannerWrapperFragment : Fragment() {
private val navController by lazy { NavHostFragment.findNavController(this) }
override fun onResume() {
super.onResume()
// forward the call to ScannerActivity
// do it in onResume to prevent call duplication from configuration changes
val intent = Intent(context, ScannerActivity::class.java)
startActivityForResult(intent, 4304357)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == 4304357) {
if (resultCode == RESULT_OK) {
val params = Bundle().apply {
putString("scan_result", data?.extras?.getString("scan_result"))
}
//present the scan results to the navigation graph
navController.navigate(R.id.action_scanner_to_result_screen, params)
} else {
navController.popBackStack()
}
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
}
我正在尝试将应用程序迁移到在 GoogleIO'18
上宣布的新 Navigation Architecture Component假设我需要使用通常以 startActivityForResult
开头的 activity。这个activity来自图书馆或系统activity,所以我无法修改它。
有什么方法可以将此 activity 作为目的地包含在导航图中并从中获取结果吗?
到目前为止,我唯一的解决方案是将 activity 包裹在捕获结果的片段后面,然后将其呈现给导航图:
class ScannerWrapperFragment : Fragment() {
private val navController by lazy { NavHostFragment.findNavController(this) }
override fun onResume() {
super.onResume()
// forward the call to ScannerActivity
// do it in onResume to prevent call duplication from configuration changes
val intent = Intent(context, ScannerActivity::class.java)
startActivityForResult(intent, 4304357)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == 4304357) {
if (resultCode == RESULT_OK) {
val params = Bundle().apply {
putString("scan_result", data?.extras?.getString("scan_result"))
}
//present the scan results to the navigation graph
navController.navigate(R.id.action_scanner_to_result_screen, params)
} else {
navController.popBackStack()
}
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
}