14

我正在尝试将应用迁移到在 GoogleIO'18 上宣布的新导航架构组件

假设我需要使用通常以startActivityForResult. 此活动来自库或系统活动,因此我无法修改它。

有没有办法将此活动作为目的地包含在导航图中并从中获取结果?

4

1 回答 1

3

到目前为止,我唯一的解决方案是将该活动包装在一个片段后面,该片段捕获结果,然后将其呈现给导航图:

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

    }

}
于 2018-05-29T13:34:14.117 回答