1
votes

I know how to make multiple top-level destinations for a navigation graph. Following the answers here is fine.

However I want to add, based on app user's desire (e.g. a button click), another top-level destination.

In compliance with the documentation :

//Redoing the navigation setup
int[] itemsId = new int[ menu.size() ];
for( int i = 0; i < menu.size(); i++ ) {
    itemsId[i] = menu.getItem(i).getItemId();        
}
mAppBarConfiguration = new AppBarConfiguration.Builder( itemsId )
    .setDrawerLayout(drawer)
    .build();
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);

This piece of code was already in onCreate() of MainActivity.java file. Then after I add an menuItem I'm running the code again.

After navigating, the newly added menuItem still shows the back button on the top left, instead of the hamburger stack button.

Is what I want even possible ? Any ideas ?

P.S : I'm using the basic project template "Navigation Drawer Activity" of Android (when you want to start a new project).

1

1 Answers

1
votes

Actually it works as long as the menu item id matches the id of the fragment in the mobile_navigation element. (It's ok to have a fragment which is not assigned to a menu item, and later add the menu item). My mistake was that I was adding a menu item dynamically like this :

int idOfNewMenuItem = View.generateViewId();
final MenuItem createdMenuItem = menu.add( R.id.main_drawer_group, idOfNewMenuItem, 0, userInputText);

then I was navigating to a fragment which has its own id

navController.navigate( R.id.nav_activefragment );

So what had to be done was

final MenuItem createdMenuItem = menu.add( R.id.main_drawer_group, R.id.nav_activefragment, 0, userInputText);
navController.navigate( R.id.nav_activefragment );

Then I have to insert again the code in the question.