Android Jetpack Navigation library and onActivityResult

纵然是瞬间 提交于 2019-12-04 02:53:48

The only solution I have so far is to wrap that activity behind a fragment that catches the result and then presents it to the navigation graph:

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)
        }

    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!