我想在片段中使用导航组件。
我的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()不起作用。
如何在片段中使用导航组件