In Navigation Component, how can one detect if fragment is brought to front from a pop event?
I go from A to B, now I close B using back key, it returns to A, now in A (in onViewCreated event) I want to detect it's coming from B.
In Navigation Component, how can one detect if fragment is brought to front from a pop event?
I go from A to B, now I close B using back key, it returns to A, now in A (in onViewCreated event) I want to detect it's coming from B.
If we're using a single NavController.
findNavController((R.id.nav_host_fragment)
.addOnDestinationChangedListener{ hostController, destination, _ ->
val push = currentBackStackSize < hostController.bacStack.size // else pop
// Then save current backstack size
}
This solution might not be always correct, but currently I can't think of an edge case. Please feel free to correct me.
Here is my solution.
In A, add a navigation argument with default value false
(in the nav_graph.xml)
In B, add a navigation back to A. To handle back button pressed, add the following in onCreate()
requireActivity().onBackPressedDispatcher.addCallback {
val action = BDirections.actionBFragmentAFragment(true)
findNavController().navigate(action)
}
Now you can determine how A appears. Also, use popUpTo to handle circular logic properly. Let me know if you see any flaws in this approach.