首页 > 解决方案 > 是否可以将 DI 与 androidx.navigation.NavController 一起使用

问题描述

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

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

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

标签: androiddependency-injectiondagger-2android-architecture-componentsandroidx

解决方案


NavController我不明白为什么在有方法可以找到它时要注入它,而且由于持有对Activity.

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

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

推荐阅读