How can I refresh the ActionBar when onPrepareOptionsMenu switched menu entries?

后端 未结 10 1401
予麋鹿
予麋鹿 2020-12-02 12:05

Within my apps I often enable/disable menu entries and do make them visible from onPrepareOptionsMenu.

Today I started to add the android:showAsAction menu attribute

10条回答
  •  一整个雨季
    2020-12-02 12:30

    Kudos to @Klaasvaak for showing us the way here. I use the following which works on both pre- and post- API Level 11:

    private void invalidOptionsMenuHelper() {
        if (Build.VERSION.SDK_INT >= 11) {
            invalidateOptionsMenu();
    
        } else if (mOptionsMenu != null) {
            mOptionsMenu.clear();
            onCreateOptionsMenu(mOptionsMenu);
        }
    }
    

    Of course, you must save a reference to the menu (mOptionsMenu in this case) which I accomplish via:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        mOptionsMenu = menu;
    
        //... create and manage the menu normally
    }
    

提交回复
热议问题