Android custom menu

By | 2 February 2011

Menus are very important in Android application because they offer an easy way to access application functions and settings. The menus are binded with the current activity. The menu raise when it pressed the menu button on your device.
To create a custom menu for our application, we follow these simply steps:

  • Define the menu and its items
  • Handling the event menu button of the device
  • Manage a selected item

DEFINE THE MENU

Define the menu is a very simple step. We just create a xml file in /res/menu/ directory of the our project like this:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/setting"
          android:icon="@drawable/ic_setting"
          android:title="@string/setting" />
    <item android:id="@+id/quit"
          android:icon="@drawable/ic_quit"
          android:title="@string/quit" />
</menu>

The xml above is composed by two main parts (or two tags):

  • The menu tag
  • The item tag

The menu tag is the root tag of the file. We just past and copy into our xml.
The item tag describe our menu button. It’s formed by three property:

  • android:id.  It is a unique id that we want assign to the button and we will use to refer it into the code.
  • android:icon.  It is optional and it is add an icon to the button. The icon must be placed into /res/drawable/ directory. For more info about menu icons go here.
  • android:title. The string that is showed into the menu button.

HANDLING THE EVENT MENU BUTTON

When we press the menu button on the device, the onCreateOptionsMenu method is triggered.
We just add this method on the Activity:

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
	MenuInflater inflater = getMenuInflater();
	inflater.inflate(R.menu.setting_menu, menu);
	return true;
}

The getMenuInflater() method returns a MenuInflater for the Activity.
With this object, you can call inflate(), which put a menu resource into a Menu object.
In this example, the menu resource defined by setting_menu.xml is putted into the Menu that was passed into onCreateOptionsMenu().

MANAGE A SELECTED ITEM

When the user select an item from the menu, the method onOptionsItemSelected() is called from the Activity. This method passes the MenuItem that the user selected. We can identify the menu item just calling getItem() method of the MenuItem object. This method return the unique id defined by android:id property into the xml file. We use this id to perform appropriate action.
Below there is a small example:

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
	switch (item.getItemId())
	{
		case R.id.setting:
			doSomething();
			return true;
		case R.id.quit:
			finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
	}
}

That’s all.
We have done a simple menu.