What does onPrepareOptionsMenu do?

46,133

Solution 1

Take a look in the API:

Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.

Solution 2

If you want to alter the menu before it's shown to the user, you can put code to do that into onPrepareOptionsMenu. I've used that dynamically to disable some menu options in some circumstances.

As an example of when one might want to disable a menu option, I had an app where there was a way of specifying a destination. One of my menu options was to calculate a route to the destination. However, if a destination wasn't specified, that option didn't apply, so I used onPrepareOptionsMenu to disable that menu option when it wasn't applicable.

From Android 3.0 and beyond, there's the ActionBar, which is a menu bar. The most important items go into the ActionBar itself, but then there's an overflow for when there's not enough room on the action bar. One can specify that menu items should always be in the overflow menu and never on the action bar itself. On some devices, the action bar overflow corresponds to the permanent menu button on the device, whereas on other devices which don't have a menu button the overflow menu is seen on the right hand side of the action bar as three vertical dots.

Solution 3

onCreateOptionsMenu is called once, when your activity is first created. If it returns false, no option menu is shown and onPrepareOptionsMenu is never called.

If onCreateOptionsMenu returns true, onPrepareOptionsMenu is also called before the activity is displayed, and also every time the options menu is invalidated. Use onPrepareOptionsMenu if you need to enable/disable, show/hide, or add/remove items after creating it.

If your menu does not change, use onCreateOptionsMenu.

Share:
46,133
Tutompita
Author by

Tutompita

Updated on July 14, 2022

Comments

  • Tutompita
    Tutompita almost 2 years

    I want to make Option Menu for Android, I have visit this site. In their script, I found onPrepareOptionsMenu, I try to compile and run using Android 2.3.3 compiler with and without onPrepareOptionsMenu, both works, but I didn't see any difference.

    public boolean onCreateOptionsMenu(Menu menu){
        //code here
    }
        
    public boolean onOptionsItemSelected(MenuItem item){
        //code here
    }
        
    public boolean onPrepareOptionsMenu(Menu menu){
        //code here
    }
    

    What is actually onPrepareOptionsMenu method do? Is that method important? Could I just delete the method?


    Addition

    Oh, I also hear about Action Bar in Android 3.0, it says that Action Bar is the alternative way for make Option Menu, and it using onPrepareOptionsMenu. Is that right?

    Thank you...