如何使用导航图而不默认加载片段?

时间:2020-08-07 17:10:03

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

我需要使用导航组件,并且已经设置好。导航图需要一个startDestination,它会在创建时默认加载该片段。但是,我有一个片段,我只想在现有屏幕中触发事件后显示。在准备导航到片段容器之前,如何将其保留为空?

1 个答案:

答案 0 :(得分:0)

在您的xml文件中,将您的容器声明为空的导航主机

     <fragment
            android:id="@+id/container"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

然后在您的活动中可以通过编程方式设置图形

        val navHost = NavHostFragment()
        fragmentManager.beginTransaction()
               .replace(R.id.container, navHost)
               .commit()
        val graph = navHost.navController.navInflater.inflate(R.navigation.my_navigation)
        graph.startDestination = R.id.my_fragment
        navHost.navController.graph = graph

您可以检查此link