Search code examples
androidandroid-navigationandroid-navigation-graph

How to make a `NavHostFragment` respond to `onBackPressed` when inside another Fragment?


I have an Activity with a NavHostFragment nested in a Fragment:

  • Root View of the Activity
    • Fragment
      • NavHostFragment

as I go navigating in the NavGraph, a back stack for NavHostFragment is being created. But as soon as I click on the back button of the device, instead of going to the previous Fragment of the back stack, the app closes (as if there were no back stack).

Am I missing something? Is there any coupling between the NavHostFragment and Fragment that needs to be done?


Solution

  • As mentioned on the interact programmatically with the Navigation component, it is the call to setPrimaryNavigationFragment()` that hooks Fragments up to the system back button.

    Each fragment in the hierarchy must have setPrimaryNavigationFragment() set. While the NavHostFragment may be calling that itself if you are inflating it from XML and using app:defaultNavHost="true", you also need to explicitly call it on your parent fragment.

    // In your Activity's onCreate() when you add the parent fragment
    if (savedInstanceState == null) {
        Fragment parent = new ParentFragment();
        getSupportFragmentManager().beginTransaction()
            .add(R.id.container, parent)
            .setPrimaryNavigationFragment(parent)
            .commit();
    }