Search code examples
androidandroid-navigationandroid-architecture-navigationandroid-navigation-graph

Defining a NavHostFragment inside another fragment


I have a fragment that I define a NavHostFragment inside it like this:

<fragment
        android:id="@+id/shipping_host_nav"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/shipping_nav_graph"
        app:defaultNavHost="true"/>

when trying to call findNavController method in the fragment it threw an illegal state exception and says that my view group doesn't have a NavController.

    java.lang.IllegalStateException: View androidx.core.widget.NestedScrollView{1dd5506 VFED..... ......I. 0,0-0,0} does not have a NavController set

So my question is: can I define a NavHostFragment inside another fragment? or suitable for activity only? I have searched a lot to find can I define a nav host fragment inside another fragment but I didn't find any answers.


Solution

  • I have found a solution for this exception, the findNavController() throws this exception when trying to call this method within a fragment that is not NavHostFragment or not within NavHostFragment so I made this mistake by calling this method in my fragment.
    So I have to find the controller by myself using Navigation class

    Navigation.findNavController(activity, R.id.my_nav_host_fragment)
    

    this is how to find the NavHostFragment (NavController) defined within a fragment

    I made an extension function for Fragment class so I can be easily find the nav controller using id

    fun Fragment.getFragmentNavController(@IdRes id: Int) = activity?.let {
        return@let Navigation.findNavController(it, id)
    }