Search code examples
androidnavigation-drawerandroid-navigationview

How to programmaticallly remove submenu from navigation drawer in Android?


I am developing an Android app. Firstly, let me tell you that I am not professional. What I am doing now is I am adding submenu to menu depending on a condition. But I need to do it very often in my app. But my problem is I added a submenu to the menu as first time.

But second time when I update menu depending on condition, existing submenu is not removed and new submenu is appended to navigation drawer. How can I remove submenu that is programmatically added to menu? Why my code is not removing it?

Here is my code

public void updateAuthUI()
    {
        isLoggedIn = tempStorage.getBoolean(getResources().getString(R.string.pref_is_logged_in),false);
        Menu menu = leftDrawer.getMenu();
        menu.removeItem(getResources().getInteger(R.integer.logout_item_id));
        menu.removeItem(getResources().getInteger(R.integer.login_item_id));
        menu.removeItem(getResources().getInteger(R.integer.register_item_id));
        SubMenu authSubMenu = menu.addSubMenu("Auth");

        if(isLoggedIn)
        {
            authSubMenu.add(1,getResources().getInteger(R.integer.logout_item_id),99,"Sign out");
        }
        else{
            authSubMenu.add(1,getResources().getInteger(R.integer.register_item_id),97,"Register");
            authSubMenu.add(1,getResources().getInteger(R.integer.login_item_id),98,"Sign in").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    openLoginActivity();
                    item.setChecked(true);
                    return true;
                }
            });
        }
    }

Here is the screenshot of my problem

enter image description here

As you can see Auth submenu is appended without removing existing one.


Solution

  • Try

    authSubMenu.clear();
    

    before your first

    authSubMenu.add();
    

    I just used SubMenu.clear() in an Android app where I was using a third-party library, and I needed to clear out an unwanted submenu from the action bar. (I actually wanted to remove the submenu completely, and this was the only way I could find to do it. It seemed to work.)

    That's different from your situation, where authSubMenu is a menu you just added via menu.addSubMenu("Auth"), so you would expect it to be empty. But, as you've seen, it apparently isn't empty: rather, addSubMenu("Auth") returns the existing submenu of that title. (I can't find documentation to that effect; I'm just going by the results you've reported.)

    If that really is the case, as it appears to be, then authSubMenu.clear() will remove all existing items from the submenu.