Jetpack导航库和onActivityResult

Jetpack导航库和onActivityResult

本文介绍了Android Jetpack导航库和onActivityResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to migrate an app to the new Navigation Architecture Component that was announced at GoogleIO'18

假设我需要使用通常以startActivityForResult开始的活动.此活动来自库活动或系统活动,因此我无法对其进行修改.

Suppose I need to use an activity that is normally started with startActivityForResult. This activity comes either from a library or a system activity, so I can't modify it.

是否有任何方法可以将此活动作为目的地包含在导航图中并从中获取结果?

Is there any way to include this activity as a destination in the navigation graph and get results from it?

推荐答案

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

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

    }

}

这篇关于Android Jetpack导航库和onActivityResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 12:37