4

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.

AVEbrahimi
  • 17,993
  • 23
  • 107
  • 210

2 Answers2

2

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.

Vaughn Armada
  • 439
  • 4
  • 5
  • On Fragment-A, you can add a check as below to make sure it doesn't impact any other cases: navController.addOnDestinationChangedListener{ _, destination, _ -> if(R.id.navigation_fragment_a == destination.id) {//Do your suff here } } – Rahul Rastogi May 30 '22 at 06:33
1

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.

Dino Tw
  • 3,167
  • 4
  • 34
  • 48