Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does onPrepareOptionsMenu do?

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...

like image 978
Tutompita Avatar asked May 26 '13 10:05

Tutompita


People also ask

What is onPrepareOptionsMenu?

Use onPrepareOptionsMenu if you need to enable/disable, show/hide, or add/remove items after creating it.

What is onCreateOptionsMenu in Android?

In this method, you can inflate your menu resource (defined in XML) into the Menu provided in the callback. For example: @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.game_menu, menu); return true; }


2 Answers

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.

like image 68
Tom Naessens Avatar answered Sep 22 '22 01:09

Tom Naessens


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.

like image 36
Stochastically Avatar answered Sep 21 '22 01:09

Stochastically