Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ActionBar Recreate Options Menu

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!

like image 951
Solder Smoker Avatar asked Aug 23 '12 22:08

Solder Smoker


People also ask

What is option menu in Android?

The options menu is the primary collection of menu items for an activity. It's where you should place actions that have a global impact on the app, such as "Search," "Compose email," and "Settings." See the section about Creating an Options Menu.

What is invalidateOptionsMenu?

invalidateOptionsMenu() is used to say Android, that contents of menu have changed, and menu should be redrawn. For example, you click a button which adds another menu item at runtime, or hides menu items group. In this case you should call invalidateOptionsMenu() , so that the system could redraw it on UI.


3 Answers

invalidateOptionsMenu() 

requires API level 11...

for lower API use:

supportInvalidateOptionsMenu()
like image 160
Sinan Dizdarević Avatar answered Oct 08 '22 13:10

Sinan Dizdarević


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.

like image 23
marmor Avatar answered Oct 08 '22 11:10

marmor


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

like image 32
runor49 Avatar answered Oct 08 '22 13:10

runor49