Android 导航组件:以编程方式从与家不同的目的地开始? [英] Android Navigation Component: Start at a different destination than home, programmatically?

查看:25
本文介绍了Android 导航组件:以编程方式从与家不同的目的地开始?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据 github 示例.但是,该示例为每个选项卡使用了不同的导航图,这使事情变得简单.就我而言,我需要对所有选项卡使用相同的导航图,但起始目的地与导航图中设置的主页目的地"不同.

I'm trying to implement a multiple navigation controller with multiple back stack BottomNavigationView, as per the github examples. However, the example uses a different nav graph for each tab, which makes things easy. In my case I need to use the same nav graph for all of my tabs, but with different start destinations, than the "home destination" set in the nav graph.

到目前为止,我已经设法修改了 NavigationExtensions 文件,以便为所有选项卡实现单个导航图,并且我获得了多个带有自己的后台堆栈的 navControllers,但我不知道如何在不同的目的地启动导航图.

So far I've managed to modify the NavigationExtensions file in order to achieve the single navgraph for all tabs, and I get multiple navControllers with their own back stacks, but I cannot figure out how to start a nav graph at a different destination.

我在获取导航控制器时尝试使用 .navigate,但由于它还没有附加,所以它不起作用.关于如何实现这一目标的任何想法?谢谢.

I've tried using .navigate when getting the navcontroller, but since it's not yet attached, it does not work. Any ideas on how to achieve this? Thank you.

推荐答案

我们有一个要求,其中显示的开始屏幕将取决于用户是否已登录,我们所做的如下:

We had a requirement wherein the displayed start screen would depend if the user has logged on, what we did was the following:

  1. 删除导航上的 app:startDestination XML(如果存在)
  2. 在您的主要活动的 XML 上,删除 标记内的以下字段:app:defaultNavHost="true"app:navGraph
  3. 在我们主 Activity 的 onCreate() 上,我们创建了一个 NavGraph 对象:

  1. Remove app:startDestination on the navigation XML if it exists
  2. On your main activity's XML, remove the following fields inside the <fragment> tag: app:defaultNavHost="true" and app:navGraph
  3. On our main Activity's onCreate(), we create a NavGraph object :

NavController navController = Navigation.findNavController(this, R.id.your_nav_hostfragment);    
NavGraph navGraph = navController.getNavInflater().inflate(R.navigation.your_navigation_xml);

  • 然后根据您的要求,您可以使用 setStartDestination 在 NavGraph 上设置起始目的地,然后将 NavGraph 应用到 NavController:

  • Then depending on your requirement, you can set the start destination on the NavGraph using setStartDestination, then apply the NavGraph to the NavController:

        if (condition) {
            navGraph.setStartDestination(R.id.screen1);
        } else {
            navGraph.setStartDestination(R.id.screen2);
        }
        navController.setGraph(navGraph);
    

  • 这篇关于Android 导航组件:以编程方式从与家不同的目的地开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆