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

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

问题描述

我正在尝试根据BottomNavigationView 的多个导航控制器/android-architecture-components/tree/master/NavigationAdvancedSample"rel =" noreferrer> 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 文件,以实现所有选项卡的单个navgraph,并且我获得了多个带有各自后置堆栈的 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.

我已经尝试在获取navcontroller时使用 .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. 删除导航 XML 上的app:startDestination(如果存在)
  2. 在主要活动的XML上,删除< fragment> 标记内的以下字段: app:defaultNavHost ="true" app:navGraph
  3. 在主活动的 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天全站免登陆