androidfacebookandroid-optionsmenuoptions-menu

How to get the options menu to disappear without pressing back/destroying the activity


Going off my last question Why is my options menu not showing the settings menu item correctly?, The code for everything

@Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // only add the menu when the selection fragment is showing
        if (fragments[SELECTION].isVisible()) {
            if (menu.size() == 0) {
                settings = menu.add(R.string.settings);
            }
            return true;
        } else {
            menu.clear();
            settings = null;
        }
        return false;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        if (item.equals(settings)) {
            showFragment(SETTINGS, true);
            return true;
        }
        return false;
    }

What happened was I managed to login fine, and logout fine. But when I logged out, the options menu still appeared even though menu.clear was called in onPrepareOptionsMenu(alter the menu before it's shown to the user). I managed to make it disappear but clicking the back button(destroying the activity) and recreating the activity. But why is the options menu still appearing in the first place? I don't want to burden the client with pressing back to make it disappear.


Solution

  • I think depending on the version of Android you are running. As soon as you press the logout button and do the logout routine, you should also call invalidateOptionsMenu to refresh the menu.