Creating Your First Menu

You can create a menu through code or through an XML file that’s provided in the res/menu directory. The preferred method of creating a menu is to define it through XML and then inflate it into a programmable object that you can interact with. This helps separate the menu definition from the actual application code.

Defining the XML file

To define an XML menu, follow these steps:

1. Create a menu folder in the res directory.

2. Add a file by the name of list_menu.xml to the menu directory.

3. Type the following code into the list_menu.xml file.

<?xml version=”1.0” encoding=”utf-8”?>

<menu

xmlns:android=”http://schemas.android.com/apk/res/android”>

<item android:id=”@+id/menu_insert”

android:icon=”@android:drawable/ic_menu_add”

android:title=”@string/menu_insert” />

</menu>

Notice that a new string resource is included (shown in bold). You’ll create that in Step 4. The android:icon value is a built-in Android icon. The ldpi, mdpi, hdpi and xhdi versions of this icon are all built into the Android platform, so you don’t have to provide this bitmap in your drawable resources. To view other resources available, view the android.R.drawable documentation at

http://developer.android.com/reference/android/R.drawable.html

remember.eps All resources in the android.R class give your application a common user interface and user experience with the Android platform.

Get Android Application Development For Dummies, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.