[Android] Beginner Tutorials – Lesson 13. Creating a simple menu

In this lesson we will:

– create menu items

Translated by Taras Leskiv (http://android-by-example.blogspot.com/)

I guess there is no point in explaining what a menu is. It is displayed when Menu button is clicked. Let’s create our own menu.

Create a project:

Project name: P0131_MenuSimple
Build Target: Android 2.3.3
Application name: MenuSimple
Package name: ru.startandroid.develop.menusimple
Create Activity: MainActivity

Open MainActivity.java. onCreateOptionsMenu method is responsible for creating a menu. Menu object is passed to this method as a parameter. We will add our menu items into this object. The adding procedure is simple, add method is used. This method takes the text of the menu item as a parameter. Let’s add 4 items

onCreateOptionsMenu method returns a boolean result. True – show menu, False – do not show. So we could have made a checking of some condition, and as a result of this check do not show a menu returning False. We don’t need this for now, so we delegate this choice to the method of superclass, it returns True by default.

Save everything, run the application and click the emulator menu button.


Four menu items appeared. Clicking them will do nothing as listener is not implemented.

Activity is a listener and method is called onOptionsItemSelected. It receives menu item which has been clicked as a parameter – MenuItem. It is possible to define which menu item has been clicked by getTitle method. Let’s show a Toast message with the text of the menu item clicked. Method must return a boolean value at the end. And we delegate it to the superclass again:

Complete code:

It is not the best practice to define the clicked menu item by its title. Later we will do this by ID. But to do so, we have to create menu slightly differently.



Share this Post :

No comments yet.

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *