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.
To get the current fragment that's active in your Android Activity class, you need to use the supportFragmentManager object. The supportFragmentManager has findFragmentById() and findFragmentByTag() methods that you can use to get a fragment instance.
NavHostFragment provides an area within your layout for self-contained navigation to occur. NavHostFragment is intended to be used as the content area within a layout resource defining your app's chrome around it, e.g.: <androidx.drawerlayout.widget.DrawerLayout.
Show activity on this post. I solved this by first inflating the view which contains the NavHost, then using the supportFragmentManager to get the navHost Fragment and pass in my default args. Hoping that Google's Android team provides a cleaner solution to this in the future. Show activity on this post.
Navigation does not provide any mechanism for getting the implementation (i.e., the Fragment itself) of the current destination.
As per the Creating event callbacks to the activity, you should either communicate with your Fragment by
onAttach
method, casting your Activity to an instance of an interface you provideViewModel
that your Activity and Fragment use to communicate.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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With