Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get previous destination with navigation component?

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?

like image 812
Patriotic Avatar asked Jan 22 '26 11:01

Patriotic


1 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.

like image 104
Mehedi Hasan Shagor Avatar answered Jan 24 '26 01:01

Mehedi Hasan Shagor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!