简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM