11

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Patriotic
  • 2,103
  • 4
  • 26
  • 36
  • 1
    why aren't you sending some parameters along with location so that you can know that location belongs to respective fragment. – Sai Jayant Mar 15 '20 at 07:38
  • Or you can know on which fragment you were on using these code and change your preference managers LastVistedFragment const see this code https://stackoverflow.com/questions/43207043/check-if-fragment-is-currently-visible-or-no/43658331#43658331 – Sai Jayant Mar 15 '20 at 07:42
  • Your solution is good but there should be something for getting backstack from a fragment. @SaiJayant – Patriotic Mar 15 '20 at 08:46
  • what are you trying to achieve ? You want info from B to be in X ? – Biscuit Mar 15 '20 at 12:12
  • in pop backstack when you will be back to your previous fragment that method i told you also update the current showing fragment – Sai Jayant Mar 16 '20 at 07:49
  • I have not found any best solution to get the previous fragment in the currently visible fragment other than sending source id from A, B, and C to X. Thanks for the cooperation. – Patriotic Mar 16 '20 at 09:18

2 Answers2

32

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.

Mehedi Hasan Shagor
  • 750
  • 1
  • 8
  • 14
-3

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
)}