最佳答案
关键是要正确NavController
在正确的图表中导航。
我们以这个场景为例:
MainActivity
|- MainNavHost
|- NavBarFragment
| |- NestedNavHost
| | |-NestedContentFragment1
| | |-NestedContentFragment2
| |
| |- BottomNavigationView
|
|- LoginFragment
主图和嵌套图在单独的xml文件中:据我了解,这是必需的,因为导航针对不同的布局区域,因此它们需要两个不同的NavHost
s。每个Navhost
需要通过 id 引用它的图,这要求它们位于不同的资源文件中。
关键是要在特定的图表中导航,我们必须获得对正确图表所有者的引用:为此,在调用 Navigation.findNavController(view)
时, view
论据至关重要。
文档这么说
NavHostFragments register their navigation controller at the root of their view subtree such that any descendant can obtain the controller instance through the Navigation helper class's methods
例如,如果在 NavBarFragment
我们写
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
navController = Navigation.findNavController(view)
}
这里 view
是NestedNavHost
的父级 (即嵌套的 NavHostFragment
),不是后代,这意味着 findNavController
将在树中搜索上游并返回 MainNavHost
的NavController
.
如果我们改为写
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val nestedNavHostFragment = childFragmentManager.findFragmentById(R.id.nestedNavHostFragment) as? NavHostFragment
navController = nestedNavHostFragment?.navController
}
在哪里 nestedNavHostFragment
是 FragmentContainerView
的 id在布局中,我们得到了正确的 NestedNavHost
的引用。 .注意 childFragmentManager
的使用,而不是 parentFragmentManager
.
如果您仍在使用已弃用的 xml <fragment>
标签,你可以写
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val fragmentContainer = view.findViewById<View>(R.id.nestedNavHostFragment)
navController = Navigation.findNavController(fragmentContainer)
}
在哪里 nestedNavHostFragment
是 <fragment>
的 id标签。我们得到了正确的 NestedNavHost
的引用。现在,因为我们传递给 findNavController
的 View 属于 NestedNavHost
的子树。
同样,如果您需要获取对主要 NavController
的引用从 NestedContentFragment
内部,这是我们可以做的:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// we can get the innermost NavController using this view,
// because we are inside its subtree:
nestedNavController = Navigation.findNavController(view)
// we can find the outer NavController passing the owning Activity
// and the id of a view associated to that NavController,
// for example the NavHostFragment id:
mainNavController = Navigation.findNavController(activity!!, R.id.mainNavHostFragment)
}
关于android - 带有嵌套导航图的 Arch 新导航组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50730494/