在我的活动布局中,我有以下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
视图实例?
答案 0 :(得分:8)
我找到了解决方案:
//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.layout.my_nav_graph)
myNavHostFragment.navController.graph = graph
基于:Navigation Architecture Component- Passing argument data to the startDestination
答案 1 :(得分:2)
当我与DynamicNavHostFragment一起使用时,这两个答案都导致异常,所以我使用了
val navHostFragment: NavHostFragment = supportFragmentManager
.findFragmentById(R.id. my_nav_host_fragment) as NavHostFragment
navHostFragment.findNavController().setGraph(R.navigation. my_nav_graph)
答案 2 :(得分:1)
您可以按如下所示在“活动”中编写内容。
findNavController(R.id.my_nav_host_fragment).setGraph(R.navigation.my_nav_graph)