带有底部导航和片段的嵌套导航图(以编程方式)

时间:2020-03-10 11:48:59

标签: android navigation

我正在尝试使用Jetpack导航组件绑定到底部导航视图,以及处理复杂的嵌套导航。对我来说,具有挑战性的是,整个底部菜单项都是动态的,并且在运行时从API中获取。因此,我需要在不使用XML的情况下以编程方式定义导航图。

我编写的代码可以在底部导航中正常工作

在主要活动中:

private val navController: NavController by lazy { findNavController(R.id.nav_host_fragment) }
private lateinit var navGraphBuilder: NavGraphBuilder

navGraphBuilder = NavGraphBuilder(navController.navigatorProvider,View.generateViewId(),menuItems[0].id.hashCode()) // create graphbuilder with startDestination of first menu item
    val bottomNav = bottom_navigation_view!!

    menuItems.forEachIndexed { index, it ->
        bottomNav.menu.add(Menu.NONE,it.id.hashCode(),Menu.NONE,it.title).icon =
            getIconDrawable(this,it.icon)
        navGraphBuilder.fragment<PageFragment>(it.id.hashCode()) //add each fragment to builder
        val i = index + 1
        if( i < menuItems.size) {
            navGraphBuilder.action(View.generateViewId()) { // add next bottom menu item as the action of current one
                this.destinationId = menuItems[i].id.hashCode()
            }
        }
    }



    bottomNav.apply {
        setBackgroundColor(ColorManager.secondaryColor)
        setupWithNavController(navController)
    }

    navController.setGraph(navGraphBuilder.build())

以上代码在创建导航图并将其绑定到底部导航时效果很好。我不知道该怎么做,是从底部菜单片段之一导航到新片段。

比方说,我的底部菜单有3个片段A BC。然后从片段A中单击打开新片段(detailsFragment)的项目。 detailsFragment还具有一些相关内容,用户可以单击它们并打开新的detailsFragment等。

我现在所拥有的是在MainActvity中(它可以打开一个新的detailsFragment):

override fun navigate(contentItem: ContentItem) { //create a new navigation graph
    val vdId = View.generateViewId()
    val selectedId = bottom_navigation_view.selectedItemId

    val m = menuItems.find {
        it.id.hashCode() == selectedId
    } // find selected menu item
    val bundle = bundleOf(CONTENT_ITEM_KEY to contentItem)
    val newNavController: NavController = findNavController(R.id.nav_host_fragment)
    val newNavGraphBuilder = NavGraphBuilder(newNavController.navigatorProvider,View.generateViewId(),m!!.id.hashCode())
//create a new graph with destination id of current selected menu item
    newNavGraphBuilder.apply {
        fragment<PageFragment>(m.id.hashCode()) //add the current menu item to grapg
        action(View.generateViewId()){
            this.destinationId = vdId
        }
        fragment<VideoDetailsFragment>(vdId) //add new detailsFragment to graph
    }
    newNavController.apply {
        graph = newNavGraphBuilder.build()
        navigate(vdId,bundle) //navigate to detailsGraph
    }

}

这也可以,但是,如果我从pageFragment中打开detailsFragment,则底部菜单将不再起作用。

我找不到任何文档或示例。感谢任何帮助

0 个答案:

没有答案