android - 是否可以将 DI 与 androidx.navigation.NavController 一起使用

标签 android dependency-injection dagger-2 android-architecture-components androidx

所以,这个标题反射(reflect)了这个问题。
要获得导航 Controller (androidx.navigation.NavController) 上的链接,我们通常使用以下代码:

NavController navController = Navigation.findNavController(this, R.id.nav_host_frag);

有没有可能注入(inject) 使用 Dagger2 的导航 Controller 框架? (findNavController 需要 Activity 或 View 引用)
也许这是一个愚蠢的问题,没有人注入(inject) androidx.navigation.NavController ,但尽管如此,我还是决定在我的假设中提出这个问题。提前谢谢

最佳答案

我不明白你为什么要注入(inject) NavController当有方法可以找到它时,由于持有对 Activity 的引用,我也会担心使用依赖注入(inject)。 .

鉴于您正在使用 Activity您通常会使用以下方法找到 Controller :

private val navController: NavController by lazy { findNavController(R.id.main_container) }

现在,如果我们看一下 findNavController() 方法的源代码你会注意到它使用了一个扩展函数和 Navigation.findNavController(this, viewId) .
/**
 * Find a [NavController] given the id of a View and its containing
 * [Activity].
 *
 * Calling this on a View that is not a [NavHost] or within a [NavHost]
 * will result in an [IllegalStateException]
 */
fun Activity.findNavController(@IdRes viewId: Int): NavController =
        Navigation.findNavController(this, viewId)

我唯一要做的补充上述内容是创建另一个扩展函数以方便从 Fragment 导航。 .
fun Fragment.navigate(resId: Int, bundle: Bundle? = null) {
    NavHostFragment.findNavController(this).navigate(resId, bundle)
}

然后你可以简单地在 fragment 中使用:
navigate(
    R.id.action_fragmentA_to_FragmentB,
    bundleOf(Global.CAN_NAVIGATE_BACK to false)
)

关于android - 是否可以将 DI 与 androidx.navigation.NavController 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55026171/

相关文章:

java - 如何使用随添加的每个子项而递增的 key 将子项添加到 Firebase 数据库?

c# - 如何设置 Unity 注册约定?

android - Mockito Android 单元测试

java - 如何避免在 Activity 中设置我所有组件的模块以注入(inject) Dagger 2 的依赖项?

android - 如何在对话框中添加多个 TextView

java - 安卓工作室 : support package v7 seems not imported correctly

java - 使用标题行扩展 fragment 容器

c# - 干净的代码 : Readable Dependency Injection suggestions?

javascript - Head.js `.js()` 方法

安卓| Dagger 2.根据条件将不同的子类注入(inject)Fragment