How do you return to the previous fragment when using a NavController?

5.2k views Asked by At

I am using a navigation graph to navigate Fragments on Android. Currently, I can go from one fragment to another and return on a back press.

Now I need to return to the previous Fragment in an OnClickListener imbedded in a FloatingActionButton hosted in an Activity that hosts the Fragment instead of a back press.

Currently, the following code takes me all the way to the beginning fragment:

NavController navController = NavHostFragment.findNavController(FragmentSelect.this);
            navController.setGraph(R.navigation.nav_graph, bundle);
            navController.popBackStack();

I have also tried getActivity().onBackPressed(); which also takes me back to the beginning fragment.

How do you return to the previous Fragment? I am trying to follow this guide, Pass data to the start destination, for returning a Bundle to a start destination, but it leaves out how to return to a start destination.

I also thought about creating another action to return to the start destination, but then the back button will return to the wrong Fragment. Is there a way to stop that?

1

There are 1 answers

4
CommonsWare On BEST ANSWER

If all that you want to do is pop the back stack, setGraph() is unnecessary. Just call popBackStack() on your NavController.