Android OptionsMenu Tutorial

Menu is an important user interface component which provides some action options for a particular activity. In this post I’ll show the basics for setting up a menu.

The final output will look like this:

android options menu

The activity will contain 2 menu options: Add and Help. When clicking an option menu, a Toast notification will be displayed.

 

1. Create a new project in Eclipse:
Project: MenuTest
Activity: MenuTestActivity

2. Android provides a standard XML format to define menu items. So, instead of building the menu in the activity’s code, we will use the XML resource. Later, the XML resource is inflated in the code.

Inside the res/ folder create a new folder called menu. Inside the menu folder create a new XML file: options.xml

android options menu xml

3. Fill in the content of options.xml file with following code:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
   <item
      android:id="@+id/add"
      android:icon="@android:drawable/ic_menu_add"
      android:title="Add"/>

   <item
      android:id="@+id/help"
      android:icon="@android:drawable/ic_menu_help"
      android:title="Help"/>
</menu>

menu – defines the menu
item  – defines a menu item

 

4. Open the main Activity class and type following code:

public class MenuTestActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);
}

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

// Handle click events
@Override
public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()) {
   case R.id.add:
      Toast.makeText(this, "Add", Toast.LENGTH_SHORT).show();
      return true;
   case R.id.help:
      Toast.makeText(this, "Help", Toast.LENGTH_SHORT).show();
      return true;

   default:
      return super.onOptionsItemSelected(item);
}
}
}

– The onCreateOptionsMenu() method inflates your menu defined in the XML resource.

– The onOptionsItemSelected() method handle click events. When the user selects an item from the options menu, the system calls the onOptionsItemSelected() method. This method passes the MenuItem selected. The MenuItem can identify the item by calling the getItemId() which returns the unique ID for the menu item defined by the android:id attribute in the menu resource. Depending of the returned ID, we display the appropriate Toast notification.

 

5. Finally, run the application and click the “Menu” button on the emulator to launch the menu.

android menu button

Advertisement