android - 是否可以将 DI 与 androidx.navigation.NavController 一起使用
问题描述
所以,这个标题反映了这个问题。要获得导航控制器 ( androidx.navigation.NavController
) 上的链接,我们通常使用以下代码:
NavController navController = Navigation.findNavController(this, R.id.nav_host_frag);
是否可以使用框架注入NavController Dagger2
?(findNavController
需要活动或视图参考)也许这是一个愚蠢的问题,没有人注入androidx.navigation.NavController
,但尽管如此,我还是决定在我的假设中提出这个问题。提前谢谢
解决方案
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)
)
推荐阅读
- java - 如何修复位图在android中调整捕获图像的大小
- javascript - 将道具数据传递给我只能通过路由访问的组件
- objective-c - 在iOS中解析json时将重复值与单个数组合并
- javascript - 是否可以在 HTML 文件中使用 React 组件?
- ios - 如何将 [NSManageObject] 数组“向下转换”到所选实体?
- kotlin - RetryWhen 中需要使用 AtomicBoolean
- glassfish-2.x - 如何在 Eclipse 中为 glassfish 2.1 服务器安装 glassfish 工具
- enums - Bison/Yacc 错误:字段类型不完整
- delphi - 为什么我收到调用错误:找不到方法
- php - PHP:CURL 返回空数据