4

I would like to attach a callback to when the Android Navigation Controller navigates up from a specific fragment (findNavController().navigateUp()). How can I achieve this functionality?

I've already heard about requireActivity().onBackPressedDispatcher.addCallback(this). This only listens to the system's back button not the back arrow on the toolbar. I'd like to listen to the event where the user presses the back arrow on the toolbar in the top-left corner.

Adifyr
  • 2,649
  • 7
  • 41
  • 62
  • Did you ever find a solution to this? I am facing the same issue. The OnBackPressedDispatcher only overrides the OS/System back button and not the Toolbar when using Android Navigation controller. – Bilal Soomro Dec 29 '19 at 18:22

2 Answers2

3

I have managed to find a solution. Here's what the onCreate() of my MainActivity looks like:

val navController = findNavController(R.id.nav_host_fragment)
val appBarConfiguration = AppBarConfiguration(navController.graph)
my_toolbar.setupWithNavController(navController, appBarConfiguration)

// The code below solved it for me. It overrides the toolbar back and then calls the OS back which is overridden in my fragment.
my_toolbar.setNavigationOnClickListener {
    onBackPressed()
}

And in my fragment, I do this in onActivityCreated()

requireActivity().onBackPressedDispatcher.addCallback(this) {
    // override custom back
}

Now I can override both toolbar back button and OS back button in a single handler.

Bilal Soomro
  • 661
  • 1
  • 7
  • 12
0

In your MainActivity that contains the NavHostFragment you can add onDestinationChanged to the NavController listener

navController = findNavController(MainActivity.this, R.id.navHostFragment);
navController.addOnDestinationChangedListener(this);

@Override
public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
    int destinationId = destination.getId();
    if (destinationId == R.id.YOUR_DESIRED_FRAGMENT_ID) // your own behavior...
}

you can then add any behavior you desire.

I hope this help.

  • How do I know what the previous destination is? I want it to happen only from a **specific fragment** to another **specific fragment**. – Adifyr Aug 28 '19 at 13:36
  • Then I believe you can add your desired behavior this specific fragment `onPause()` or `onDestroy()`. – Ahmed Fathy Aug 29 '19 at 11:01