Android ActionBar Recreate Options Menu

家住魔仙堡 提交于 2019-12-10 01:56:49

问题


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!


回答1:


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




回答2:


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.




回答3:


invalidateOptionsMenu() 

requires API level 11...

for lower API use:

supportInvalidateOptionsMenu()


来源:https://stackoverflow.com/questions/12100641/android-actionbar-recreate-options-menu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!