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

Author: Rachee Singh -- Published? true -- FormatLanguage: W

Problem:

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

Solution:

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

Discussion:

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:title="One" 
        android:icon="@drawable/first" />
    <item android:id="@+id/icon2"
        android:title="Two" 
        android:icon="@drawable/second" />
    <item android:id="@+id/icon3"
        android:title="Three"
        android:icon="@drawable/three" />
    <item android:id="@+id/icon4"
        android:title="Four"
        android:icon="@drawable/four" />
</menu> 
    

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 :


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

This is how it looks:

No records found.