Setting NavGraph programmatically

时光毁灭记忆、已成空白 提交于 2020-06-25 10:00:43

问题


In my activity layout, I have the following 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" />

My question is how can I set the navGraph programmatically? How can I convert the my_nav_host_fragment view instance in a NavHostFragment instance?


回答1:


I found a solution:

//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

Based on: Navigation Architecture Component- Passing argument data to the startDestination




回答2:


You can write in your Activity as follows.

findNavController(R.id.my_nav_host_fragment).setGraph(R.navigation.my_nav_graph)


来源:https://stackoverflow.com/questions/50898996/setting-navgraph-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!