MonoDroid – creating an options menu
One of the standard Android buttons that is required to be on every phone is the “menu” button. This brings up a little options menu on the bottom of the screen with icons and text labels that perform some action. For instance, on the main screen of the official Twitter app, you’ll get an options menu with two buttons: “Settings” and “Sign out”.
It’s easy to add an options menu with MonoDroid.
In the activity class, just override two methods: OnCreateOptionsMenu and OnOptionsItemSelected. The first one will construct a menu when the user hits the menu button. The second will respond to the action they clicked. Here’s how my code looks right now:
The “Add” method overload on the IMenu that I’m using takes arguments: groupId, itemId, order, title, respectively. GroupId and ItemId almost seem arbitrary to me at this point. Order is the numeric order of how the options will be displayed, and title is the text that will appear with the icon.
Note that there is no Add overload with a parameter to specify the icon. I added a refresh icon to the project (since MonoDroid doesn’t seem to have Android.R.Drawable.IcMenuRefresh yet for some reason) named “ic_menu_refresh.png”, so once I get the option added, I turn right around and give it an icon with the SetIcon method.
I’m switching on the title of the option selected, which may or may not be good practice, but it works fine. You could also switch on the ItemId (see above) if you want. Note that the “ToS” is just an extension method that I wrote because I was tired of getting jerked around by the weird Java string/ToString stuff. The “Refresh” option only calls the Refresh method that I’m using elsewhere. Finally, while the default case might never happen, notice that this method returns a “bool”, so it’s a good catch-all that leaves the rest of the work to the super class.
That’s option menus in a quick nutshell. An easy way to add common functionality without junking up your layout. Feel free to take a look at the complete code at my MonodroidStockPortfolio project on GitHub.