Search code examples
androidandroid-optionsmenuoncreateoptionsmenu

How do I only trigger onPrepareOptionsMenu and not onCreateOptionsMenu?


According to the Android menu documentation and a similar question, onPrepareOptionsMenu should be used to update menus dynamically. For Android 3.0 and higher, the documentation says:

When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu()

However, when calling invalidateOptionsMenu(), the system calls both, onCreateOptionsMenu() and onPrepareOptionsMenu(). Resuming the activity also either calls both methods (if it was stopped in background) or none.

To me, this sounds like the differentiation between the two methods is obsolete. Is there any situation in which Android only calls onPrepareOptionsMenu() but not onCreateOptionsMenu()? Additionally, is there a way to manually request that Android only calls onPrepareOptionsMenu(), like it is implied in the documentation (cited below)?

[onCreateOptionsMenu()] is only called once, the first time the options menu is displayed. To update the menu every time it is displayed, see onPrepareOptionsMenu(Menu).

Thank you very much!


Solution

  • You are using Activity menu here, so assuming you have single activity app it will be only inflated once, during onCreateOptionsMenu - that's the scenario with a single call.
    If you want to change it, then you have to invalidate the current one and inflate a new one - as it's an app's global menu it only make sense if you want to change its contents - you do that using onPrepareOptionsMenu and then inflate it again in onCreateOptionsMenu call.

    But if you make lots of menu changes then it amy be better to use to use Fragment specific menus - they only live as long as the their fragment - menus

    So to answer your specific question - you cannot NOT trigger the onCreateOptionsMenu. You can override it to do absolutely nothing but then the menu will not be inflated

    EDIT - it seems I misunderstood the documentation as well. The key bit for onPrepareOptionsMenu is:

    This is called right before the menu is shown, every time it is shown.

    Which in practice means that every time you click on the Menu onPrepareOptionsMenu will be called, without calling onCreateOptionsMenu