可以在androidx.navigation.NavController中使用DI

问题描述 投票:0回答:2

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

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

是否可以使用Dagger2框架注入NavController? (findNavController需要一个活动或视图参考)也许这是一个愚蠢的问题,没有人注入androidx.navigation.NavController,但尽管如此,我决定在我的假设中提出这个问题。谢谢你

android dependency-injection dagger-2 android-architecture-components androidx
2个回答
1
投票

当你有找到它的方法时,我不明白你为什么要注入NavController,我也会因为持有对Activity的引用而使用依赖注入。

鉴于您正在使用Activity,您通常会使用以下方法找到控制器:

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

然后你可以简单地在片段中使用:

navigate(
    R.id.action_fragmentA_to_FragmentB,
    bundleOf(Global.CAN_NAVIGATE_BACK to false)
)

0
投票

为什么不能这样做?您可以像任何其他对象一样将其添加到组件中

  • 通过@BindsInstance的Component.Builder或带参数的模块
  • 通过从@Provides注释方法返回它

使用@Provides带注释的方法,您还需要在组件中提供活动或视图。根据您使用Dagger的方式,您通常会使用特定的活动,因此您可以使用它,例如对于带有MyActivityComponentMyActivity,您可以简单地将其返回到模块中

@Provides
NavController bindController(MyActivity activity) {
  Navigation.findNavController(this, R.id.nav_host_frag)
}
© www.soinside.com 2019 - 2024. All rights reserved.