Android (java): Update bottom navigation items depending on whether user is signed in or not

Viewed 17

I have a bottom navigation with 5 items. Depending on whether the user is signed in or not, only 4 items should be visible (item 4 only shows if the user is signed in and item 5 only shows if the user is not signed in).

In MainActivity, I created the updateBottomNavigation() function, which is called from the SignInFragment:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Set up the toolbar
    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Set up the navController
    FragmentManager supportFragmentManager = getSupportFragmentManager();
    NavHostFragment navHostFragment = (NavHostFragment) supportFragmentManager.findFragmentById(R.id.nav_host_fragment);
    navController = navHostFragment.getNavController();

    // Set up the app bar
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(R.id.homeFragment, R.id.libraryFragment, R.id.searchFragment, R.id.myStuffFragment, R.id.promptFragment).build();
    NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration);

    // Connect bottom navigation
    bottomNav = findViewById(R.id.bottom_nav);
    NavigationUI.setupWithNavController(bottomNav, navController);

    
    });

public void updateBottomNavigation(String userType) {

    if (userType.equals("subscriber")) {
        if (bottomNav.getMenu().findItem(R.id.promptFragment) != null) {
            bottomNav.getMenu().removeItem(R.id.promptFragment);
        }
    } else if (userType.equals("visitor")) {
        if (bottomNav.getMenu().findItem(R.id.myStuffFragment) != null) {
            bottomNav.getMenu().removeItem(R.id.myStuffFragment);
        }
    } 
}

When the app loads for the first time, the MyStuff item does not appear. However, when the user signs in, the Prompt item disappears but the My Stuff item does not reappear, because it has been already removed at the beginning.

Is there a way to refresh the bottom navigation so it loads from scratch before calling the updateBottomNavigation() method? Or a way to not remove the menu item but hide it instead so that it can be made visible when needed?

1 Answers

You can toggle the visibility of a menu item:

MenuItem promptItem = bottomNav.getMenu().findItem(R.id.promptFragment);
MenuItem myStuffItem = bottomNav.getMenu().findItem(R.id.myStuffFragment);
if (userType.equals("subscriber")) {
    if ( promptItem != null) {
        promptItem.setVisibility(VIEW.GONE);
    }
    if ( myStuffItem != null) {
        myStuffItem .setVisibility(VIEW.VISIBLE);
    }
} else if (userType.equals("visitor")) {
     if ( myStuffItem != null) {
        myStuffItem .setVisibility(VIEW.GONE);
    }
} 
Related