Defining Menus in XML

Android lets you define your Menu hierarchies as XML resources.

As with layouts and other resources, this gives you the ability to create different Menus for alternative hardware configurations, languages, or locations. For example, you may wish to move some onscreen options to your menu for small displays.

Menu resources are created as XML files in the res/menu folder of your resources directory. Each menu hierarchy must be created as a separate file, for which the lowercase file name becomes the resource identifier.

Create your Menu hierarchy using the <menu> tag as the root node and a series of <item> tags to specify each Menu Item. Each item node supports attributes to specify the Menu Item properties, including the text, icon, shortcut, and checkbox options.

To create a submenu, simply place a new <menu> tag as a subnode within an <item>.

Listing 4-30 shows how to create the Menu hierarchy described in Listing 4-29 as an XML resource.

LISTING 4-30: Defining a menu in XML Available for download on <menu xmlns:android="http://schemas.android.com/apk/res/android" Wrox.com android:name="Context Menu">

<item android:id="@+id/item01"

Prepared for ASHLEE KABAT, email: [email protected] Order number: 56760408 This PDF is for the purchaser's personal use in accordance with the Wrox Terms of Service and under US copyright as stated on this book's copyright page. If you did not purchase this copy, please visit www.wrox.com to purchase your own copy.

android:icon="@drawable/menu_item" android:title="item 1"> </item> <item android:id="@+id/item02" android:checkable="true" android:title="item 2"> </item> <item android:id="@+id/item03" android:numericShortcut="3" android:alphabeticShortcut="3" android:title="item 3"> </item> <item android:id="@+id/item04" android:title="Submenu"> <menu> <item android:id="@+id/item05" android:title="Submenu item"> </item> </menu> </item> </menu>

To use your Menu resource, use the Menuinflator class within your onCreateOptionsMenu or onCreateContextMenu event handlers, as shown in Listing 4-31.

LISTING 4-31: Inflating an XML menu resource

Available for download on Wrox.com public void onCreateContextMenu(ContextMenu menu, View v,

ContextMenu.ContextMenuInfo menulnfo) { super.onCreateContextMenu(menu, v, menulnfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.my_menu, menu); menu.setHeaderTitle("Context Menu");

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide


Post a comment