Search code examples
androidandroid-fragmentsandroid-architecture-navigation

How an Activity can be notified of NavHostFragment child fragments attachement


I'm having an Activity, containing a NavHostFragment with a given navigation graph (and classic child fragments). My child fragments may trigger events (declared through an interface), so they have a method setXXXlistener(Interface) to register a listener implementing the interface.

That's the Activity that may implement the interface (because it knows what to do on the events).

To do that, I was expecting the Activity.onAttachFragment method will be called when child fragments were displayed, in order to do something like :

public void onAttachFragment(@NonNull Fragment fragment)
{
    super.onAttachFragment(fragment);
    if( fragment instanceof OneOfMyFragment)
    {
        ((OneOfMyFragment)fragment).setXXXListener(this);
    }
}

but it's not the case ; onAttachFragment is called once with the NavHostFragment argument.

So I looked into the NavHostFragment, and the solution may be using NavHostFragment.getChildFragmentManager() which returns a FragmentManager, then I can do FragmentManager.addFragmentOnAttachListener(listener), so I will be able to do my own registration.

The problem is : FragmentManager.addFragmentOnAttachListener seems to be documented but not defined in the source file ! (At least AndroidStudio don't know it and won't compile)

In my gradle files, I currently have those versions (but also tried with API 30) :

compileSdkVersion 29
buildToolsVersion "29.0.2"

targetSdkVersion 29

and

implementation 'androidx.navigation:navigation-fragment:2.3.2'
implementation 'androidx.navigation:navigation-ui:2.3.2'

Any idea ? (to achieve my goal, or to solve the undefined error)


Solution

  • androidx.navigation:navigation-fragment:2.3.2 only depends on Fragment 1.2.4, but the addFragmentOnAttachListener API was added only in Fragment 1.3.0-alpha06. Therefore, you need to specifically add a dependency on a Fragment 1.3 version (currently, 1.3.0-rc01) if you want to use that new API:

    implementation 'androidx.navigation:navigation-fragment:2.3.2'
    implementation 'androidx.navigation:navigation-ui:2.3.2'
    
    // Add this line
    implementation 'androidx.fragment:fragment:1.3.0-rc01'