9

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.

Shalan93
  • 774
  • 1
  • 7
  • 20
  • I have found this when trying to understand why the exception is thrown * @throws IllegalStateException if the given Fragment does not correspond with a * {@link NavHost} or is not within a NavHost. – Shalan93 Nov 06 '19 at 22:20
  • Also, I found this Navigation component is scoped to a single Activity is this means navigation component nav host working only with activity? – Shalan93 Nov 07 '19 at 09:12

1 Answers1

10

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)
}
Shalan93
  • 774
  • 1
  • 7
  • 20
  • 1
    If you are using `navigation-ktx`, you can just call `activity?.findNavController(id)` and not have to create an extension function for that – Max Feb 23 '20 at 06:32
  • I've seen your post at **dev.to** and here in **StackOverflow**. I've tried to solve this issue in different ways but my app keeps crashing. I appreciate if you could shed some light on the issue I am facing: https://stackoverflow.com/q/60962539/4300670 – Aliton Oliveira Apr 02 '20 at 20:50
  • can u pls share the complete implementation ? I m stuck at same. – AndroidGuy Dec 31 '20 at 06:09