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
I post my complete answer with androidx. Care : in my case i needed to retrieve one of the child fragment (could not be the first).
In MainActivity you should have something like :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.mytest, R.id.nav_help)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
...
Then you have to create a method to retrieve the good fragment.
private MyTestFragment getMyTestFragment(){
MyTestFragment resultFragment = null;
Fragment navHostFragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
if(navHostFragment != null && navHostFragment.getChildFragmentManager() != null) {
List fragmentList = navHostFragment.getChildFragmentManager().getFragments();
for (Fragment fragment : fragmentList) {
if (fragment instanceof MyTest) {
resultFragment = (MyTest) fragment;
break;
}
}
}
return resultFragment;
}
Finally you get it.