How I can retrieve current fragment in NavHostFragment?

后端 未结 8 1309
遇见更好的自我
遇见更好的自我 2020-12-15 17:06

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 :

mainHostFrag         


        
相关标签:
8条回答
  • 2020-12-15 17:38

    From an Activity which has NavHostFragment, below code snippet can be used to retrieve the instance of the Active Fragment.

    kotlin

    val currentFragment = mNavHostFragment?.childFragmentManager?.primaryNavigationFragment

    java

    Fragment navHostFragment = getSupportFragmentManager().getPrimaryNavigationFragment();
    Fragment currentFragment = navHostFragment.getChildFragmentManager().getFragments().get(0);
    
    0 讨论(0)
  • 2020-12-15 17:42

    Reference to the displayed fragment (AndroidX):

    public Fragment getForegroundFragment(){
        Fragment navHostFragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
        return navHostFragment == null ? null : navHostFragment.getChildFragmentManager().getFragments().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"

    0 讨论(0)
提交回复
热议问题