如何在 activity 中获取 navController?

How to get navController inside activity?

我使用 Jetpack Navigation 在片段和 activity 之间导航。所以,我在布局中有一个 MainActivity 和一个 FragmentContainerView。我可以轻松地从片段导航到 fragment/activity。但是,我找不到使用 navController.

从一个 activity 导航到另一个 activity/fragment 的方法

例如,从片段 FA,我调用 navController.navigate() 到 activity A。现在,我想从 activity A 导航到 activity B 或片段 FB .

我已经试过了:

val host = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = host.navController

但总是出现这个错误

null cannot be cast to non-null type androidx.navigation.fragment.NavHostFragment

谢谢!

导航组件指南中的注释

Note: The Navigation component is designed for apps that have one main activity with multiple fragment destinations. The main activity is associated with a navigation graph and contains a NavHostFragment that is responsible for swapping destinations as needed. In an app with multiple activity destinations, each activity has its own navigation graph.

您不应使用导航组件从一个 activity 导航到另一个。它用于交换片段容器上的片段。

您可以使用

activity中得到navController
val navHostFragment =
        supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController

您还必须将 android:name="androidx.navigation.fragment.NavHostFragment" 添加到您的片段容器

<androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
/>

对于java编码器;

可以通过这种方式获取 NavController 实例

NavHostFragment navHostFragment =(NavHostFragment)getSupportFragmentManager()
                                     .findFragmentById(R.id.nav_host_fragment);

NavController navController = navHostFragment.getNavController();