Issue
I want to use Navigation component in my fragment.
My XML code like this
<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>
And Initializing navigation code like this.
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)
}
}
And after I launched my app, I got an error message like this.
View androidx.fragment.app.FragmentContainerView{... app:id/fragment_nav_host_home} does not have a NavController set
Also, findNavController() does not work.
How can I use navigation component in my fragment
Solution
Kotlin Answer
Key point is that try to use childFragmentManager in onViewCreated() function.
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
}
Answered By - DevPolarBear
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.