以编程方式设置 NavGraph



在我的活动布局中,我有以下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" />

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

我找到了一个解决方案:

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

基于:导航体系结构组件 - 将参数数据传递到开始目标

您可以在您的活动中编写如下内容。

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

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

val navHostFragment: NavHostFragment = supportFragmentManager
.findFragmentById(R.id. my_nav_host_fragment) as NavHostFragment
navHostFragment.findNavController().setGraph(R.navigation. my_nav_graph)

我的解决方案是这样的,

val myNavHostFragment = supportFragmentManager
.findFragmentById(R.id.navHostFragmentMain) as NavHostFragment
val inflater = myNavHostFragment.navController.navInflater
val graph = inflater.inflate(R.navigation.nav_graph)
myNavHostFragment.navController.graph = graph

相关内容

  • 没有找到相关文章

最新更新