Defining a NavHostFragment inside another fragment
R

1

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.

Requisition answered 6/11, 2019 at 21:49 Comment(2)
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.Requisition
Also, I found this Navigation component is scoped to a single Activity is this means navigation component nav host working only with activity?Requisition
R
11

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)
}
Requisition answered 7/11, 2019 at 9:53 Comment(3)
If you are using navigation-ktx, you can just call activity?.findNavController(id) and not have to create an extension function for thatPyretic
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://mcmap.net/q/1315574/-constraintlayout-does-not-have-a-navcontroller-set-for-item-clicked-on-recyclerview/4300670Sambo
can u pls share the complete implementation ? I m stuck at same.Ackack

© 2022 - 2024 — McMap. All rights reserved.