Android ActionBar Recreate Options Menu

Solder Smoker picture Solder Smoker · Aug 24, 2012 · Viewed 8.7k times · Source

When using the ActionBar in Android, how do you refresh the options menu? I have tried hiding and showing the bar, along with getting a new instance of it with "getSupportActionBar()"

I am trying to implement a Login/Logout button that will change dynamically based on the state of the user.

Here is my onCreateOptionsMenu method

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (loggedIn)
        menu.add(0, MENU2, 0, "Logout").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    else
        menu.add(0, MENU2, 0, "Login").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    menu.add(0, MENU1, 0, "Home").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    return super.onCreateOptionsMenu(menu);
}

Thanks!

Answer

runor49 picture runor49 · Aug 24, 2012

Invalidate the menu with invalidateOptionsMenu() and then put your code in the onPrepareOptionsMenu area.