Android ActionBar Recreate Options Menu

2019-04-21 09:16发布

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!

3条回答
虎瘦雄心在
2楼-- · 2019-04-21 09:57

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

查看更多
做自己的国王
3楼-- · 2019-04-21 09:57

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.

查看更多
Juvenile、少年°
4楼-- · 2019-04-21 10:05
invalidateOptionsMenu() 

requires API level 11...

for lower API use:

supportInvalidateOptionsMenu()
查看更多
登录 后发表回答