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
Showing the DialogFragment Instead, use the show() method to display your dialog. You can pass a reference to a FragmentManager and a String to use as a FragmentTransaction tag.
NavController manages app navigation within a NavHost . Apps will generally obtain a controller directly from a host, or by using one of the utility methods on the Navigation class rather than create a controller directly. Navigation flows and destinations are determined by the navigation graph owned by the controller.
Dialog: A dialog is a small window that prompts the user to make a decision or enter additional information. DialogFragment: A DialogFragment is a special fragment subclass that is designed for creating and hosting dialogs.
Android DialogFragments. DialogFragment is a utility class which extends the Fragment class. It is a part of the v4 support library and is used to display an overlay modal window within an activity that floats on top of the rest of the content. Essentially a DialogFragment displays a Dialog but inside a Fragment.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With