Unable to find NavController that's inside a DialogFragment
Asked Answered
P

2

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

Paff answered 13/9, 2019 at 21:41 Comment(3)
did you try fragment.findNavController()?Levalloisian
@Levalloisian I did yes, there was not differencePaff
@PavSidhu please show us the nav graph containing dialog fragmentFirestone
S
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.

Scalage answered 23/9, 2019 at 13:38 Comment(0)
S
-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.

Stamen answered 23/9, 2019 at 15:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.