我正在尝试将应用程序迁移到新的 Navigation Architecture Component这是在 GoogleIO'18 上宣布的
假设我需要使用通常以 startActivityForResult
启动的 Activity 。此 Activity 来自库或系统 Activity ,因此我无法修改它。
有什么方法可以将此 Activity 作为目的地包含在导航图中并从中获取结果吗?
最佳答案
到目前为止,我唯一的解决方案是将该 Activity 包装在捕获结果的 fragment 后面,然后将其呈现给导航图:
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)
}
}
}
关于Android Jetpack 导航库和 onActivityResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50488351/