所以,这个标题反射(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/