Search code examples
androidandroid-navigationandroid-jetpack

Android Navigation Architecture Component - Get current visible fragment


Before trying the Navigation component I used to manually do fragment transactions and used the fragment tag in order to fetch the current fragment.

val fragment:MyFragment = supportFragmentManager.findFragmentByTag(tag):MyFragment

Now in my main activity layout I have something like:

<fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/nav_host"
        app:navGraph= "@navigation/nav_item"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:defaultNavHost= "true"
        />

How can I retrieve the current displayed fragment by the Navigation component? Doing

supportFragmentManager.findFragmentById(R.id.nav_host)

returns a NavHostFragment and I want to retrieve my shown 'MyFragment`.

Thank you.


Solution

  • I managed to discover a way for now and it is as follows:

    NavHostFragment navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host);
    navHostFragment.getChildFragmentManager().getFragments().get(0);
    

    In case of course you know it is the first fragment. I am still investigating a way without this. I agree it is not the best way but that should be something for now.