15

在我的活动布局中,我有以下内容NavHostFragment

<fragment
            android:id="@+id/my_nav_host_fragment"
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:name="androidx.navigation.fragment.NavHostFragment"
            app:defaultNavHost="true"
            app:navGraph="@navigation/my_nav_graph" />

我的问题是如何以编程方式设置 navGraph?如何在my_nav_host_fragment实例中转换视图NavHostFragment实例?

4

3 回答 3

36

我找到了一个解决方案:

//Setup the navGraph for this activity
val myNavHostFragment: NavHostFragment = my_nav_host_fragment as NavHostFragment
val inflater = myNavHostFragment.navController.navInflater
val graph = inflater.inflate(R.navigation.my_nav_graph)
myNavHostFragment.navController.graph = graph

基于:导航架构组件-将参数数据传递给 startDestination

于 2018-06-17T18:22:36.047 回答
5

你可以在你的活动中写如下。

findNavController(R.id.my_nav_host_fragment).setGraph(R.navigation.my_nav_graph)
于 2020-05-13T16:25:34.863 回答
3

当我与 DynamicNavHostFragment 一起使用时,这两个答案都导致了异常,所以我使用了

val navHostFragment: NavHostFragment = supportFragmentManager
    .findFragmentById(R.id. my_nav_host_fragment) as NavHostFragment

navHostFragment.findNavController().setGraph(R.navigation. my_nav_graph)
于 2020-08-18T07:25:06.473 回答