gpt4 book ai didi

android - 如何在 Activity 中获取 navController?

转载 作者:行者123 更新时间:2023-12-01 23:12:24 28 4
gpt4 key购买 nike

我使用 Jetpack Navigation 在 fragment 和 Activity 之间导航。因此,我在布局中有一个带有 FragmentContainerViewMainActivity。我可以轻松地从 fragment 导航到 fragment/Activity 。但是,我找不到如何使用 navController 从一个 Activity 导航到另一个 Activity/fragment 的方法。

例如,我从 fragment FA 调用 navController.navigate() 到 Activity A。现在,我想从 Activity A 导航到 Activity B 或 fragment 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 。它用于交换 fragment 容器上的 fragment 。

您可以使用 activity 获取 navController

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

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

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

关于android - 如何在 Activity 中获取 navController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69594295/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com