11

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!

Solder Smoker
  • 283
  • 1
  • 6
  • 14
  • possible duplicate of [Refreshing the Action Bar in Android 3.0](http://stackoverflow.com/questions/6602534/refreshing-the-action-bar-in-android-3-0) – CommonsWare Aug 23 '12 at 22:05
  • General Question - What is Stackoverflow etiquette for choosing a best answer when two answers are the same and answered within about the same time of each other as well? – Solder Smoker Aug 23 '12 at 22:12
  • Better answers (more detail, code samples, links, etc.) trump faster answers. For answers of equivalent merit in both areas... flip a coin? – CommonsWare Aug 23 '12 at 22:15

3 Answers3

15

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

runor49
  • 3,870
  • 1
  • 21
  • 18
12

In your FragmentActivity call invalidateOptionsMenu()

This is also a public method, so if you want to refresh it from a fragment call getActivity().invalidateOptionsMenu()

BTW, if you're using SherlockActionBar you'll need to call getSherlockActivity().invalidateOptionsMenu() from the fragment, or you'll get an exception.

marmor
  • 27,641
  • 11
  • 107
  • 150
9
invalidateOptionsMenu() 

requires API level 11...

for lower API use:

supportInvalidateOptionsMenu()