6

I have a BottomSheetDialogFragment that contains a NavHostFragment like so:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <fragment
                android:id="@+id/add_feeling_nav_host_fragment"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                app:defaultNavHost="true"
                app:navGraph="@navigation/add_feeling_graph" />

    </LinearLayout>
</layout>

When I try to get the NavController in it's class using either of the following:

activity?.findNavController(R.id.add_feeling_nav_host_fragment)
view.findNavController()

The first option crashes because it cannot find the ID and the second one does finds a parent Nav Controller and uses that.

I have an identical setup for another Fragment however it's not a dialog and it works perfectly. Any ideas to what the issue could be? Thanks

Pav Sidhu
  • 6,724
  • 18
  • 55
  • 110

2 Answers2

5

activity?.findNavController(R.id.add_feeling_nav_host_fragment) won't do the job - it will work only if the dialog fragment is active(showing) and it is a part of activity`s UI container - DialogFragment works in other instance of window that is not within the same hierarchy with the root nav graph.

Appropriate way to do it - with NavHostFragment.findNavController(fragment) or ktx extension fragment.findNavController() where fragment is your dialog fragment. The dialog fragment should be showing with its view inflated. The best way to do it - within the dialog.

Navigation graph adjustments may also be required - I cannot tell exactly since there is no code.

Hope it helps.

Pavlo Ostasha
  • 14,527
  • 11
  • 35
-1

Well, first of all you should post more code for us to see the whole picture. One small detail is that you dont need neither <layout> and <LinearLayout> in navigation xml. Fragment is just ok. I will suggest you to look at this repository, there is exactly solution you need.

I Hope it helps.

Kebab Krabby
  • 1,574
  • 13
  • 21