Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 463
BenjaminBihr Avatar asked Jun 04 '18 21:06

BenjaminBihr


People also ask

How do you get current visible fragments?

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.

What is NAV host fragment?

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.

How do I get NavHostFragment in activity?

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.


2 Answers

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.
like image 102
ianhanniballake Avatar answered Oct 09 '22 11:10

ianhanniballake


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"

like image 20
isabsent Avatar answered Oct 09 '22 11:10

isabsent