Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Creating and Displaying a Menu

In Chapter: GUI Alerts: Menus, Dialogs, Toasts and Notifications
Author: Rachee Singh ('racheesingh')
Published? true
FormatLanguage: WikiFormat


Within the Activity, showing a menu on pressing the Menu button of the Android device.


Implement a menu by setting it up in the XML and attaching it to your Activity by overriding onCreateOptionsMenu().


Its a two step process:

Step 1: Create a directory named 'menu' in the res directory of the project. In the menu directory create a menu.xml. Here is the code for menu.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/icon1"
        android:icon="@drawable/first" />
    <item android:id="@+id/icon2"
        android:icon="@drawable/second" />
    <item android:id="@+id/icon3"
        android:icon="@drawable/three" />
    <item android:id="@+id/icon4"
        android:icon="@drawable/four" />

In this XML code we add a menu and to it we add as many items as our application requires. We can images (in this case default images have been added).

Step 2: In the java code for the activity, override the onCreateOptionsMenu :

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

This is how it looks: