Pages

Thursday, 21 April 2011

Adding a Menu to your Android app

Adding an Android Menu to your app that opens when the hardware menu button is pressed

This is very simple so we'll jump straight into the XML file that defines the menu. Typically menu XML definitions will be kept in a menu folder within the resources folder; res. Create the directory if it is missing and add a new XML file called 'example.xml'.

The following full path should now exists within your project:

  res/menu/example.xml

Open the XML file and paste in XML below. Here we are defining a menu with a single item labelled "Refresh". This item has an icon, but this is not a requirement:

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

Now open the activity class that you want to include the menu in. Add the following imports at the top of the class:

import android.view.Menu;
  import android.view.MenuInflater;
  import android.view MenuItem;

Two methods are required within your activity class, the first creates the menu options by inflating the xml definition we created:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.example, menu);
        return true;
    }
   
The second method handles the menu item selection. Here I use a case statement to react in response to the ID of the tapped menu item:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_refresh:
            // Refresh something
            return true; 
        default:
            return super.onOptionsItemSelected(item);
        }
    }

Now run your app and hit the menu button and you should see something like this...

Android app with menu

For more detail please refer to the Android Developer Creating Menus guide.

0 comments:

Post a Comment