I tried to find a method in the new Navigation components but I didn't find anything about that.
I have the current destination with :
mainHostFragment.findNavController().currentDestination
But I can't get any reference to the displayed fragment.
Reference to the displayed fragment (AndroidX):
java
public Fragment getForegroundFragment(){
Fragment navHostFragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
return navHostFragment == null ? null : navHostFragment.getChildFragmentManager().getFragments().get(0);
}
kotlin
val navHostFragment: Fragment? =
supportFragmentManager.findFragmentById(R.id.nav_host_fragment)
navHostFragment?.childFragmentManager?.fragments?.get(0)
Here nav_host_fragment
is an ID
of the fragment
tag in your activity_main.xml
with android:name="androidx.navigation.fragment.NavHostFragment"