You are on page 1of 6


Android - Creating Menus


On-line Guides

All Guides eBook Store iOS / Android Linux for Beginners Office Productivity Linux Installation Linux Security Linux Utilities Linux Virtualization Linux Kernel System/Network Admin Programming Scripting Languages Development Tools Web Development GUI Toolkits/Desktop Databases Mail Systems openSolaris Eclipse Documentation

Previous Page User Interface >

Android Development
Home Next Page

Creating Menus
Menus are an important part of any application. They provide familiar interfaces that reveal application functions and settings. Android offers an easy programming interface for developers to provide standardized application menus for various situations. Android offers three fundamental types of application menus: Options Menu This is the primary set of menu items for an Activity. It is revealed by pressing the device MENU key. Within the Options Menu are two groups of menu items: Icon Menu This is the collection of items initially visible at the bottom of the screen at the press of the MENU key. It supports a maximum of six menu items. These are the only menu items that support icons and the only menu items that do not support checkboxes or radio buttons. Expanded Menu This is a vertical list of items exposed by the "More" menu item from the Icon Menu. It exists only when the Icon Menu becomes over-loaded and is comprised of the sixth Option Menu item and the rest. Context Menu This is a floating list of menu items that may appear when you perform a long-press on a View (such as a list item). Submenu This is a floating list of menu items that is revealed by an item in the Options Menu or a Context Menu. A Submenu item cannot support nested Submenus.

How To Guides

Virtualization General System Admin Linux Security Linux Filesystems Web Servers Graphics & Desktop PC Hardware Windows Problem Solutions

Options Menu
The Options Menu is opened by pressing the device MENU key. When opened, the Icon Menu is displayed, which holds the first six menu items. If more than six items are added to the Options Menu, then those that can't fit in the Icon Menu are revealed in the Expanded Menu, via the "More" menu item. The Expanded Menu is automatically added when there are more than six items.

iPhone iOS 5 Development Essentials The Options Menu is where you should include basic application functions and any eBook $12.99 (eBook) necessary navigation items (e.g., to a home screen or application settings). You $27.99 (Print) can also add Submenus for organizing topics and including extra menu functionality.

When this menu is opened for the first time, the Android system will call the Activity o C e t O t o s e u )callback method. Override this method in your nraepinMn( Activity and populate the Menu object given to you. You can populate the menu by inflating a menu resource that was defined in XML, or by calling a d )for each item d( you'd like in the menu. This method adds a MenuItem, and returns the newly created object to you. You can use the returned MenuItem to set additional properties like an icon, a keyboard shortcut, an intent, and other settings for the item. There are multiple a d )methods. Usually, you'll want to use one that accepts an itemId argument. This is a d( unique integer that allows you to identify the item during a callback. 1/6

When a menu item is selected from the Options Menu, you will recieve a callback to the

RHEL 6 Essentials eBook $9.99



When a menu item is- selected Menusthe Options Menu, you will recieve a callback to the Android Creating from o O t o s t m e e t d )method of your Activity. This callback passes you the M n I e that has been npinIeSlce( eutm selected. You can identify the item by requesting the itemId, with g t t m d ) which returns the integer that eIeI(, was assigned with the a d )method. Once you identify the menu item, you can take the appropriate action. d( Here's an example of this procedure, inside an Activity, wherein we create an Options Menu and handle item selections: / Cetstemn ies* * rae h eu tm / pbi boenoCetOtoseuMn mn){ ulc ola nraepinMn(eu eu mn.d(,MN_E_AE 0 "e Gm"; euad0 EUNWGM, , Nw ae) mn.d(,MN_UT 0 "ut) euad0 EUQI, , Qi"; rtr tu; eun re } / Hnlsie slcin * * ade tm eetos / pbi boenoOtostmeetdMnIe ie){ ulc ola npinIeSlce(eutm tm sic (tmgttmd) { wth ie.eIeI() cs MN_E_AE ae EUNWGM: nwae) eGm(; rtr tu; eun re cs MN_UT ae EUQI: qi(; ut) rtr tu; eun re } rtr fle eun as; } The a d )method used in this sample takes four arguments: groupId, itemId, order, and title. The groupId d( allows you to associate this menu item with a group of other items (more about Menu groups, below) in this example, we ignore it. itemId is a unique integer that we give the MenuItem so that can identify it in the next callback. order allows us to define the display order of the item by default, they are displayed by the order in which we add them. title is, of course, the name that goes on the menu item (this can also be a string resource, and we recommend you do it that way for easier localization). Tip: If you have several menu items that can be grouped together with a title, consider organizing them into a Submenu.

Adding icons
Icons can also be added to items that appears in the Icon Menu with s t c n ) For example: eIo(. mn.d(,MN_UT 0 "ut) euad0 EUQI, , Qi" .eIo(.rwbemn_utio) stcnRdaal.euqi_cn;

Modifying the menu

If you want to sometimes re-write the Options Menu as it is opened, override the o P e a e p i n M n ( nrprOtoseu) method, which is called each time the menu is opened. This will pass you the Menu object, just like the o C e t O t o s e u )callback. This is useful if you'd like to add or remove menu options depending on the nraepinMn( current state of an application or game. Note: When changing items in the menu, it's bad practice to do so based on the currently selected item. Keep in mind that, when in touch mode, there will not be a selected (or focused) item. Instead, you should use a Context Menu for such behaviors, when you want to provide functionality based on a particular item in the UI.

Context Menu
The Android context menu is similar, in concept, to the menu revealed with a "right-click" on a PC. When a view is registered to a context menu, performing a "long-press" (press and hold for about two seconds) on the object will reveal a floating menu that provides functions relating to that item. Context menus can be registered to any View object, however, they are most often used for items in a ListView, which helpfully indicates the presence of the context menu by transforming the background color of the ListView item when pressed. (The items in the phone's contact list offer an example of this feature.) Note: Context menu items do not support icons or shortcut keys. To create a context menu, you must override the Activity's context menu callback methods: o C e t C n e t e u )and o C n e t t m e e t d ) Inside the o C e t C n e t e u )callback method, nraeotxMn( notxIeSlce(. nraeotxMn( you can add menu items using one of the a d )methods, or by inflating a menu resource that was defined in d( XML. Then, register a ContextMenu for the View, with r g s e F r o t x M n ( . eitroCneteu) For example, here is some code that can be used with the Notepad application to add a context menu for each note in the list: pbi vi oCetCneteuCneteumn,Ve v ulc od nraeotxMn(otxMn eu iw , CneteunomnIf){ otxMnIf euno sproCetCneteumn,v mnIf) ue.nraeotxMn(eu , euno;



s p r o CAndroid nCreatingu m n , v m n I f ) u e . n r a e o t x M nMenus etC - ete (eu , euno; mn.d(,EI_D 0 "dt) euad0 DTI, , Ei"; mn.d(,DLT_D 0 "eee) euad0 EEEI, , Dlt"; } pbi boenoCnettmeetdMnIe ie){ ulc ola notxIeSlce(eutm tm AatrotxMnIf if =(dpeCneteuno ie.eMnIf(; dpeCneteuno no AatrotxMnIf) tmgteuno) sic (tmgttmd) { wth ie.eIeI() cs EI_D ae DTI: eiNt(noi) dtoeif.d; rtr tu; eun re cs DLT_D ae EEEI: dltNt(noi) eeeoeif.d; rtr tu; eun re dfut eal: rtr sproCnettmeetdie) eun ue.notxIeSlce(tm; } } In o C e t C n e t e u ) we are given not only the ContextMenu to which we will add MenuItems, but also the nraeotxMn(, View that was selected and a ContextMenuInfo object, which provides additional information about the object that was selected. In this example, nothing special is done in o C e t C n e t e u ) just a couple items are nraeotxMn( added as usual. In the o C n e t t m e e t d )callback, we request the AdapterContextMenuInfo from the notxIeSlce( M n I e , which provides information about the currently selected item. All we need from this is the list ID for eutm the selected item, so whether editing a note or deleting it, we find the ID with the A a t r o t x M n I f . n ofield of the object. This ID is passed to the e i N t ( and d l t N t ( dpeCneteunoif dtoe) eeeoe) methods to perfrom the respective action. Now, to register this context menu for all the items in a ListView, we pass the entire L s V e to the itiw r g s e F r o t x M n ( i w method: eitroCneteuVe) rgseFrotxMn(eLsVe() eitroCneteugtitiw); Remember, you can pass any View object to register a context menu. Here, g t i t i w )returns the ListView eLsVe( object used in the Notepad application's ListActivity. As such, each item in the list is registered to this context menu.

A sub menu can be added within any menu, except another sub menu. These are very useful when your application has a lot of functions that may be organized in topics, like the items in a PC application's menu bar (File, Edit, View, etc.). A sub menu is created by adding it to an existing Menu with a d u M n ( . This returns a SubMenu object (an dSbeu) extension of Menu). You can then add additional items to this menu, with the normal routine, using the a d ) d( methods. For example: pbi boenoCetOtoseuMn mn){ ulc ola nraepinMn(eu eu boenrsl =sproCetOtoseumn) ola eut ue.nraepinMn(eu; SbeuflMn =mn.dSbeu"ie) uMn ieeu euaduMn(Fl"; SbeueiMn =mn.dSbeu"dt) uMn dteu euaduMn(Ei"; flMn.d(nw) ieeuad"e"; flMn.d(oe"; ieeuad"pn) flMn.d(sv"; ieeuad"ae) eiMn.d(ud"; dteuad"no) eiMn.d(rd"; dteuad"eo) rtr rsl; eun eut } Callbacks for items selected in a sub menu are made to the parent menu's callback method. For the example above, selections in the sub menu will be handled by the o O t o s t m e e t d )callback. npinIeSlce( You can also add Submenus when you define the parent menu in XML.

Define Menus in XML

Just like Android UI layouts, you can define application menus in XML, then inflate them in your menu's o C e t . . )callback method. This makes your application code cleaner and separates more interface design nrae.( into XML, which is easier to visualize. To start, create a new folder in your project r s directory called m n . This is where you should keep all XML e/ eu files that define your application menus. In a menu XML layout, there are three valid elements: < e u , < r u >and < t m . The i e and g o p mn> gop ie> tm ru elements must be children of a m n , but i e elements may also be the children of a g o p and another m n eu tm ru, eu element may be the child of an i e tm eu (to create a Submenu). Of course, the root node of any file must be a m n 3/6


element may Android child of an i e (to create a Submenu). Of course, the root node of any file must be a m n be the - Creating Menus tm eu element. As an example, we'll define the same menu created in the Options Menu section, above. We start with an XML file named o t o s m n . m inside the r s m n /folder: pin_euxl e/eu <euxlsadod"tp/shmsadodcmakrsadod> mn mn:nri=ht:/cea.nri.o/p/e/nri" <tmadodi=@i/e_ae ie nri:d"+dnwgm" adodtte"e Gm"/ nri:il=Nw ae > <tmadodi=@i/ut ie nri:d"+dqi" adodtte"ut / nri:il=Qi" > <mn> /eu Then, in the o C e t O t o s e u )method, we inflate this resource using M n I f a e . n l t ( : nraepinMn( eunltrifae) pbi boenoCetOtoseuMn mn){ ulc ola nraepinMn(eu eu MnIfae ifae =gteunltr) eunltr nltr eMnIfae(; ifae.nlt(.euotosmn,mn) nltrifaeRmn.pin_eu eu; rtr tu; eun re } The g t e u n l t r )method returns the MenuInflater for our activity's context. We then call i f a e ) eMnIfae( nlt(, passing it a pointer to our menu resource and the Menu object given by the callback. While this small sample may seem like more effort, compared to creating the menu items in the o C e t O t o s e u )method, this will save a lot of trouble when dealing with more items and it keeps your nraepinMn( application code clean. You can define menu groups by wrapping i e elements in a g o pelement, and create Submenus by nesting tm ru another m n inside an i e . Each element also supports all the necessary attributes to control features like eu tm shortcut keys, checkboxes, icons, and more. To learn about these attributes and more about the XML syntax, see the Menus topic in the Available Resource Types document.

Menu Features
Here are some other features that can be applied to most menu items.

Menu groups
When adding new items to a menu, you can optionally include each item in a group. A menu group is a collection of menu items that can share certain traits, like whether they are visible, enabled, or checkable. A group is defined by an integer (or a resource id, in XML). A menu item is added to the group when it is added to the menu, using one of the a d )methods that accepts a groupId as an argument, such as a d i t i t d( d(n, n, it it. n, n) You can show or hide the entire group with s t r u V s b e ) enable or disable the group with eGopiil(; s t r u E a l d ) and set whether the items can be checkable with s t r u C e k b e ) eGopnbe(; eGophcal(.

Checkable menu items

Any menu item can be used as an interface for turning options on and off. This can be indicated with a checkbox for stand-alone options, or radio buttons for groups of mutually exlusive options (see the screenshot, to the right). Note: Menu items in the Icon Menu cannot display a checkbox or radio button. If you choose to make items in the Icon Menu checkable, then you must personally indicate the state by swapping the icon and/or text each time the state changes between on and off. To make a single item checkable, use the s t h c a l ( method, like so: eCekbe) mn.d(,VBAESTIGI,0 "irt" euad0 IRT_ETN_D , Vbae) .eCekbetu) sthcal(re; This will display a checkbox with the menu item (unless it's in the Icon Menu). When the item is selected, the o O t o s t m e e t d )callback is called as npinIeSlce( usual. It is here that you must set the state of the checkbox. You can query the current state of the item with i C e k d )and set the checked state with shce( s t h c e ( . Here's what this looks like inside the o O t o s t m e e t d )callback: eCekd) npinIeSlce( sic (tmgttmd) { wth ie.eIeI() cs VBAESTIGI: ae IRT_ETN_D i (tmiCekd) ie.eCekdfle; f ie.shce() tmsthce(as) es ie.eCekdtu) le tmsthce(re; rtr tu; eun re .. . } 4/6


Android - Creating Menus To make a group of mutually exclusive radio button items, simply assign the same group ID to each menu item and call s t r u C e k b e ) In this case, you don't need to call s t h c a l ( on each menu items, eGophcal(. eCekbe) because the group as a whole is set checkable. Here's an example of two mutually exclusive options in a Submenu: Sbeusbeu=mn.dSbeu"oo"; uMn uMn euaduMn(Clr) sbeuadCLRMN_RU,CLRRDI,0 "e"; uMn.d(OO_EUGOP OO_E_D , Rd) sbeuadCLRMN_RU,CLRBU_D 0 "le) uMn.d(OO_EUGOP OO_LEI, , Bu"; sbeustruCekbeCLRMN_RU,tu,tu) uMn.eGophcal(OO_EUGOP re re; In the s t r u C e k b e )method, the first argument is the group ID that we want to set checkable. The eGophcal( second argument is whether we want the group items to be checkable. The last one is whether we want each item to be exclusively checkable (if we set this false, then all the items will be checkboxes instead of radio buttons). When the group is set to be exclusive (radio buttons), each time a new item is selected, all other are automatically de-selected. Note: Checkable menu items are intended to be used only on a per-session basis and not saved to the device (e.g., the Map mode setting in the Maps application is not saved screenshot above). If there are application settings that you would like to save for the user, then you should store the data using Preferences, and manage them with a PreferenceActivity.

Shortcut keys
Quick access shortcut keys using letters and/or numbers can be added to menu items with s t l h b t c h r c t c a )(to set char shortcut), s t u e i S o t u ( n )(to set numeric shortcut), or eApaeiSotu(hr eNmrchrctit s t h r c t c a , n )(to set both). Case is not sensitive. For example: eSotu(hrit mn.d(,MN_UT 0 "ut) euad0 EUQI, , Qi" .eApaeiSotu(q) stlhbtchrct''; Now, when the menu is open (or while holding the MENU key), pressing the "q" key will select this item. This shortcut key will be displayed as a tip in the menu item, below the menu item name (except for items in the Icon Menu). Note: Shortcuts cannot be added to items in a Context Menu.

Menu item intents

If you've read the Application Fundamentals, then you're at least a little familiar with Android Intents. These allow applications to bind with each other, share information, and perform user tasks cooperatively. Just like your application might fire an Intent to launch a web browser, an email client, or another Activity in your application, you can perform such actions from within a menu. There are two ways to do this: define an Intent and assign it to a single menu item, or define an Intent and allow Android to search the device for activities and dynamically add a menu item for each one that meets the Intent criteria. For more information on creating Intents and providing your application's services to other applications, read the Intents and Intent Filters document.

Set an intent for a single menu item

If you want to offer a specific menu item that launches a new Activity, then you can specifically define an Intent for the menu item with the s t n e t )method. eItn( For example, inside the o C e t O t o s e u )method, you can define a new menu item with an Intent like nraepinMn( this: MnIe mnIe =mn.d(,POOPCE_D 0 "eetPoo) eutm eutm euad0 HT_IKRI, , Slc ht"; mnIe.eItn(e Itn(hs Pooikrcas) eutmstnetnw netti,; Android will automatically launch the Activity when the item is selected. Note: This will not return a result to your Activity. If you wish to be returned a result, then do not use s t n e t ) Instead, handle the selection as usual in the o O t o s e u t m e e t d )or eItn(. npinMnIeSlce( o C n e t e u t m e e t d )callback and call s a t c i i y o R s l ( . notxMnIeSlce( trAtvtFreut)

Dynamically add intents

If there are potentially multiple activities that are relevant to your current Activity or selected item, then the application can dynamically add menu items that execute other services. During menu creation, define an Intent with the category Intent.ALTERNATIVE_CATEGORY and/or Intent.SELECTED_ALTERNATIVE, the MIME type currently selected (if any), and any other requirements, the same way as you would satisfy an intent filter to open a new Activity. Then call a d n e t p i n ( to have dItnOtos) Android search for any services meeting those requirements and add them to the menu for you. If there are no applications installed that satisfy the Intent, then no additional menu items are added. Note: SELECTED_ALTERNATIVE is used to handle the currently selected element on the screen. So, it should 5/6


Android - Creating Menus Note: SELECTED_ALTERNATIVE is used to handle the currently selected element on the screen. So, it should only be used when creating a Menu in o C e t C n e t e u )or o P e a e p i n M n ( , which is called every nraeotxMn( nrprOtoseu) time the Options Menu is opened.
Here's an example demonstrating how an application would search for additional services to display on its menu. pbi boenoCetOtoseuMn mn) ulc ola nraepinMn(eu eu{ sproCetOtoseumn) ue.nraepinMn(eu; / Cet a Itn ta dsrbsterqieet t flil t b icue / rae n net ht ecie h eurmns o ufl, o e nldd / i ormn.Teofrn apms icueactgr vleo Itn.AEOYATRAIE / n u eu h feig p ut nld aeoy au f netCTGR_LENTV. Itn itn =nwItn(ul gtnet)gtaa); net net e netnl, eItn(.eDt() itn.dCtgr(netCTGR_LENTV) netadaeoyItn.AEOYATRAIE; / Sac fr adpplt temn wt,acpal ofrn apiain. / erh o, n ouae h eu ih cetbe feig plctos mn.dItnOtos euadnetpin( tiCasITN_PIN, / Mn gop hsls.NETOTOS / eu ru 0 , / Uiu ie I (oe / nqe tm D nn) 0 , / Odrfrteies(oe / re o h tm nn) ti.eCmoetae) hsgtopnnNm(, / TecretAtvt nm / h urn ciiy ae nl, / Seii iest paefrt(oe ul / pcfc tm o lc is nn) itn,/ Itn cetdaoeta dsrbsorrqieet net / net rae bv ht ecie u eurmns 0 , / Adtoa fast cnrlies(oe / diinl lg o oto tm nn) nl) / Aryo MnIesta croaet seii ies(oe ul; / ra f eutm ht orlt o pcfc tm nn) rtr tu; eun re } For each Activity found that provides an Intent Filter matching the Intent defined, a menu item will be added, using the android:label value of the intent filter as the text for the menu item. The a d n e t p i n ( dItnOtos) method will also return the number of menu items added. Also be aware that, when a d n e t p i n ( is called, it will override any and all menu items in the menu dItnOtos) group specified in the first argument. If you wish to offer the services of your Activity to other application menus, then you only need to define an intent filter as usual. Just be sure to include the ALTERNATIVE and/or SELECTED_ALTERNATIVE values in the name attribute of a < a e o y element in the intent filter. For example: ctgr> <netfle lbl"eieIae> itn-itr ae=Rsz mg" .. . <aeoyadodnm=adoditn.aeoyATRAIE / ctgr nri:ae"nri.netctgr.LENTV" > <aeoyadodnm=adoditn.aeoySLCE_LENTV"/ ctgr nri:ae"nri.netctgr.EETDATRAIE > .. . <itn-itr /netfle> read more about writing intent filters in the Intents and Intent Filters document. For a sample application using this technique, see the Note Pad sample code.
Back to User Interface Previous Page
Ads by Google

Android Development
Home Next Page

Android Application

Android on Phone

Google Android

Android Device

Publishe d unde r the te rm s fo the Apache 2.0 Lice nse

Design by Interspire