Android NavController移至另一个主机目标

时间:2019-07-11 11:49:58

标签: android kotlin android-architecture-components android-architecture-navigation

我对NavController有疑问:

有计划(对我的画很抱歉,希望对您有帮助:D)

enter image description here

我有MainActivityBottomNavigationView,带有3个标签: A,B,C

当我点击A时,它将打开Fragment A1,还有next button会打开Fragment A2

Fragment A2中有按钮backnext,此处的导航没有问题。

问题是,当我需要从Fragment A2导航到section B时,就像单击B中的BottomNavigationView一样。

问题在于它是不同的图形,如何切换它们?

我的想法:

  1. 我找到了解决方法:requireActivity().bottomBar.selectedItemId = R.id.graph_b,但这不是一个好主意。

  2. 我想使用navigation component实现它。我试图做findNavController().navigate(R.id.graph_b),但是会导致崩溃:

  

java.lang.IllegalArgumentException:导航目标   NavController未知com.my.app.staging:id / graph_b

如何使用NavController进行制作?

有一个具有所有架构的Google Example项目: https://github.com/googlesamples/android-architecture-components/tree/master/NavigationAdvancedSample

为简化我的问题,我在此项目中添加了一个按钮,单击时应打开另一个屏幕:

enter image description here

2 个答案:

答案 0 :(得分:0)

您的图表是在“家长活动”中定义的,这就是您可以控制它们的地方。

您的第一种方法实际上是解决方案。您的活动中定义了图。当您位于图A内的任何目标位置(例如A1,A2等)时,他们都不了解其他图B和C。到达图的唯一方法是通过父项活动,因此

requireActivity().bottomBar.selectedItemId = R.id.graph_b

您尝试过的第二种方法肯定不会起作用,因为嵌套导航时会使用findNavController().navigate(R.id.graph_b)。换句话说,graph_b应该放在graph_a内,这不是您的情况。

话虽如此,你可以做的就是写

requireActivity().bottomBar.selectedItemId = R.id.graph_b

鸽友。与其在片段内部运行,不如在活动内部运行。

// In your fragment
requireActivity?.moveToGraphB()

// and in your activity
fun moveToGraphB() {
    bottomBar.selectedItemId = R.id.graph_b
}

或者更多的爱好者会使用SharedViewModel,我认为这不是必需的。

答案 1 :(得分:0)

在图B中,您可以添加线

其中nav_graphA是单击按钮时要导航到的图形的名称。然后您可以添加

` <fragment
            android:id="@+id/aboutFragment"
            android:name="com.mycompany.aboutFragment"
            tools:layout="@layout/fragment_about"
            android:label="About" >
         <action
                android:id="@+id/action_aboutFragment_to_nav_graphA"
                app:destination="@id/nav_graphA" />
    </fragment>
`

创建单击按钮时进行导航的操作。

相关问题