Android Jetpack 导航库和 onActivityResult

标签 android android-activity android-jetpack android-architecture-navigation

我正在尝试将应用程序迁移到新的 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/

相关文章:

iphone - HTML5 网络应用与原生移动应用

android - Flutter - 如何在 WebView 中下载文件?

android - 标记为 "SingleTask"的 Activity 已提前

Android:多 Pane 布局上操作栏/选项菜单的设计模式

android - 如何在 Android Jetpack Compose 中更改布局子项的绘制顺序?

java - CRest日志请求/响应体

java - 添加日期选择器后时间选择器停止工作

android - 如何知道用户是否拒绝从 Google Play 游戏服务登录?

android - 为什么 Datastore 比 Shared Preferences 慢

android - 如何在撰写中控制 AnimatedVisibility 的持续时间?