18

Hello Android Developers,

I have seen a lot of question regarding the update of Options Menu. However, every answer says I have to call invalidateOptionsMenu().

My question is, is there any other way of updating the Options Menu without invoking the method invalidateOptionsMenu()?

Michael 'Maik' Ardan
  • 4,213
  • 9
  • 37
  • 60
  • 7
    Is there a reason not to use `invalidateOptionsMenu()`? That's exactly what it's there for... – Kevin Coppock Feb 14 '13 at 03:46
  • I've created a classA that extends Activity. Created classB that extends classA. classC (Invokes my XML activity) extends classC. – Michael 'Maik' Ardan Feb 14 '13 at 03:50
  • See http://stackoverflow.com/a/11699930/597657 – Eng.Fouad Feb 14 '13 at 03:53
  • Actually, I have created the OptionsMenu, I just have to update the OptionsMenu dynamically. – Michael 'Maik' Ardan Feb 14 '13 at 04:00
  • 1
    I'm still not seeing why that precludes you using `invalidateOptionsMenu()`. @Eng.Fouad has an answer you could use, but I'm still not seeing the problem, I guess. – Kevin Coppock Feb 14 '13 at 04:25
  • Actually, classC doesn't have the method invalidateOptionsMenu() – Michael 'Maik' Ardan Feb 14 '13 at 05:13
  • Plus, calling invalidateOptionsMenu() from superclass of superclass would break the encapsulation. Quoted from Skeet – Michael 'Maik' Ardan Feb 14 '13 at 05:29
  • Confirming. In my code the menu content is dependent on certain Model states and some of them are triggered in a deferred way through services work result. The logic of "onResults" could became hard to comprehend really quick and will require a lot of synchroniztion efforts. The onPrepareOptionsMenu solution helps to track all of that in a single place without any complications or fluidity impact as far as your menu changes are limited to hide/show/add/remove. Just KISS. – halxinate May 03 '16 at 22:56

1 Answers1

22
@Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        menu.clear(); // Clear the menu first

            /* Add the menu items */

        return super.onPrepareOptionsMenu(menu);
    }

This solved the problem on updating the OptionsMenu without invoking the invalidateOptionsMenu()

Michael 'Maik' Ardan
  • 4,213
  • 9
  • 37
  • 60
  • invalidateOptionsMenu calls onItemSelected of spinner in action bar i have to give a try for this! – LOG_TAG Oct 16 '13 at 06:04
  • this works! I can't use invalidateOptionsMenu because somehow after calling that, the toast that suppose to show up after long pressing menu item icon does not work anymore – Bruce Apr 26 '16 at 14:34
  • I cannot see how I could use your solution. Maybe you could help me on a similar problem that I am facing. https://stackoverflow.com/questions/54756799/android-studio-invalidateoptionsmenu-causes-the-always-visible-items-to-stop – Aliton Oliveira Feb 18 '19 at 23:32