How to get previous destination with navigation component?

Viewed 6345

I have fragments A, B, C, and X where their navigations are as the following.

 A --> X 
 B --> X 
 C --> X

How could I know the information of the last or previous destination in X?

The current destination ID can be found by

Navigation.findNavController(v).getCurrentDestination().getId()

I also tried using getBackStackEntry(int destinationId) but it returns only the topmost NavBackStackEntry for a destination id. In other words, the current destination.

Also getActivity().getSupportFragmentManager().getBackStackEntryCount(); returning 0.

Possible solutions are:

  1. Pass data from A, B, and C to X and identify the previous fragment by checking with that data.
  2. Use shared SharedViewModel.

Is it possible to get the current destination?

2 Answers

Java: Navigation.findNavController(v).getPreviousBackStackEntry().getDestination().getId();

Kotlin: findNavController().previousBackStackEntry?.destination?.id

This should return you the previous destination's id in the 'X' fragment.

add destination change listener. and compare id with A,B,C of ids on back key press

NavController.OnDestinationChangedListener { controller, destination, arguments ->
    // react on change or 
    //you can check destination.id or destination.label and act based on that
)}
Related