How I can retrieve current fragment in NavHostFragment?
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.
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
- Having the Fragment register a callback in its
onAttach
method, casting your Activity to an instance of an interface you provide -
Use a shared
ViewModel
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"
You can do something like this:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val navHostFragment = supportFragmentManager.fragments.first() as? NavHostFragment
if(navHostFragment != null) {
val childFragments = navHostFragment.childFragmentManager.fragments
childFragments.forEach { fragment ->
fragment.onActivityResult(requestCode, resultCode, data)
}
}
}
But for more advanced communication Listeners with callback methods registered in Fragment.onAttach() (Fragment -> Activity rather one direction communication
) and SharedViewModel (bidirectional
, important to have ViewModelProviders, and Lifecycle owner that is scoped to getActivity()
rather)