如何在 fragment Android 中使用导航组件

How to use navigation component in fragment Android

我想在我的片段中使用导航组件。

我的 XML 代码是这样的

 <androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    ...

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragment_nav_host_home"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:navGraph="@navigation/home_navigation"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/app_bar" />
</androidx.constraintlayout.widget.ConstraintLayout>

并像这样初始化导航代码。

class HomeFragment : Fragment() {

   //...initialie view


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val navController = Navigation.findNavController(binding.fragmentNavHostHome)
        navController.setGraph(R.navigation.home_navigation)

        val appBarConfiguration = AppBarConfiguration(navController.graph)

        NavigationUI.setupActionBarWithNavController(requireActivity() as AppCompatActivity, navController, appBarConfiguration)

    
    }

}

在我启动我的应用程序后,我收到了这样的错误消息。

View androidx.fragment.app.FragmentContainerView{... app:id/fragment_nav_host_home} does not have a NavController set

此外,findNavController() 不起作用。

如何在我的片段中使用导航组件

Kotlin 答案

重点是尝试在onViewCreated()函数中使用childFragmentManager

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

  // Define container.
  val loginDialogContainer = childFragmentManager.findFragmentById(R.id.container) as NavHostFragment

  // Set nav controller.
  val loginNavController: NavController = loginDialogContainer.navController
}