androidnavigationandroid-architecture-navigationnavigation-architecture

Detect pop in Navigation Component


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.


Solution

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