Creating Menus.docx
《Creating Menus.docx》由会员分享,可在线阅读,更多相关《Creating Menus.docx(14页珍藏版)》请在冰豆网上搜索。
CreatingMenus
CreatingMenus
Menusareanimportantpartofanapplicationthatprovideafamiliarinterfacefortheusertoaccessapplicationfunctionsandsettings.Androidoffersaneasyprogramminginterfaceforyoutoprovideapplicationmenusinyourapplication.
Androidprovidesthreetypesofapplicationmenus:
OptionsMenu
TheprimarymenuforanActivity,whichappearswhentheuserpressesthedeviceMENUkey.WithintheOptionsMenuaretwogroups:
IconMenu
ThemenuitemsvisibleatthebottomofthescreenatthepressoftheMENUkey.Itsupportsamaximumofsixmenuitems.Thesearetheonlymenuitemsthatsupporticonsandtheonlymenuitemsthatdonotsupportcheckboxesorradiobuttons.
ExpandedMenu
Theverticallistofmenuitemsexposedbythe"More"menuitemintheIconMenu.WhentheIconMenuisfull,theexpandedmenuiscomprisedofthesixthmenuitemandtherest.
ContextMenu
Afloatinglistofmenuitemsthatappearswhentheuserperformsalong-pressonaView.
Submenu
AfloatinglistofmenuitemsthattheuseropensbypressingamenuitemintheOptionsMenuoracontextmenu.Asubmenuitemcannotsupportanestedsubmenu.
DefiningMenus
InsteadofinstantiatingMenuobjectsinyourapplicationcode,youshoulddefineamenuandallitsitemsinanXMLmenuresource,theninflatethemenuresource(loaditasaprogrammableobject)inyourapplicationcode.DefiningyourmenusinXMLisagoodpracticebecauseitseparatesyourinterfacedesignfromyourapplicationcode(thesameaswhenyoudefineyourActivitylayout).
Todefineamenu,createanXMLfileinsideyourproject'sres/menu/directoryandbuildthemenuwiththefollowingelements:
Thisexampledefinesamenuwithtwomenuitems.Eachitemincludestheattributes:
android:
id
AresourceIDthat'suniquetotheitemsothattheapplicationcanrecognizetheitemwhentheuserselectsit.
android:
icon
Adrawableresourcethatistheiconvisibletotheuser.
android:
title
Astringresourcethatisthetitlevisibletotheuser.
FormoreabouttheXMLsyntaxandattributesforamenuresource,seetheMenuResourcereference.
InflatingaMenuResource
Youcaninflateyourmenuresource(converttheXMLresourceintoaprogrammableobject)usingMenuInflater.inflate().Forexample,thefollowingcodeinflatesthegame_menu.xmlfiledefinedaboveduringtheonCreateOptionsMenu()callbackmethod,tobeusedfortheOptionsMenu:
@Override
publicbooleanonCreateOptionsMenu(Menumenu){
MenuInflaterinflater=getMenuInflater();
inflater.inflate(R.menu.game_menu,menu);
returntrue;
}
ThegetMenuInflater()methodreturnsaMenuInflaterfortheActivity.Withthisobject,youcancallinflate(),whichinflatesamenuresourceintoaMenuobject.Inthisexample,themenuresourcedefinedbygame_menu.xmlisinflatedintotheMenuthatwaspassedintoonCreateOptionsMenu().(Thiscallbackmethodforcreatinganoptionmenuisdiscussedmoreinthenextsection.)
CreatinganOptionsMenu
Figure1.ScreenshotofanOptionsMenu.
TheOptionsMenuiswhereyoushouldincludebasicapplicationfunctionsandnecessarynavigationitems(forexample,abuttontoopenapplicationsettings).TheusercanopentheOptionsMenuwiththedeviceMENUkey.Figure1showsascreenshotofanOptionsMenu.
Whenopened,thefirstvisibleportionoftheOptionsMenuiscalledtheIconMenu.Itholdsthefirstsixmenuitems.IfyouaddmorethansixitemstotheOptionsMenu,AndroidplacesthesixthitemandthoseafteritintotheExpandedMenu,whichtheusercanopenwiththe"More"menuitem.
WhentheuseropenstheOptionsMenuforthefirsttime,AndroidcallsyourActivity'sonCreateOptionsMenu()method.OverridethismethodinyourActivityandpopulatetheMenuthatispassedintothemethod.PopulatetheMenubyinflatingamenuresourceasdescribedinInflatingaMenuResource.(Youcanalsopopulatethemenuincode,usingadd()toaddmenuitems.)
WhentheuserselectsamenuitemfromtheOptionsMenu,thesystemcallsyourActivity'sonOptionsItemSelected()method.ThismethodpassestheMenuItemthattheuserselected.YoucanidentifythemenuitembycallinggetItemId(),whichreturnstheuniqueIDforthemenuitem(definedbytheandroid:
idattributeinthemenuresourceorwithanintegerpassedtotheadd()method).YoucanmatchthisIDagainstknownmenuitemsandperformtheappropriateaction.
Forexample:
@Override
publicbooleanonOptionsItemSelected(MenuItemitem){
//Handleitemselection
switch(item.getItemId()){
caseR.id.new_game:
newGame();
returntrue;
caseR.id.quit:
quit();
returntrue;
default:
returnsuper.onOptionsItemSelected(item);
}
}
Inthisexample,getItemId()queriestheIDfortheselectedmenuitemandtheswitchstatementcomparestheIDagainsttheresourceIDsthatwereassignedtomenuitemsintheXMLresource.Whenaswitchcasesuccessfullyhandlestheitem,itreturns"true"toindicatethattheitemselectionwashandled.Otherwise,thedefaultstatementpassesthemenuitemtothesuperclassincaseitcanhandletheitemselected.(Ifyou'vedirectlyextendedtheActivityclass,thenthesuperclassreturns"false",butit'sagoodpracticetopassunhandledmenuitemstothesuperclassinsteadofdirectlyreturning"false".)
Tip:
IfyourapplicationcontainsmultipleactivitiesandsomeofthemprovidethesameOptionsMenu,considercreatinganActivitythatimplementsnothingexcepttheonCreateOptionsMenu()andonOptionsItemSelected()methods.ThenextendthisclassforeachActivitythatshouldsharethesameOptionsMenu.Thisway,youhavetomanageonlyonesetofcodeforhandlingmenuactionsandeachdecendentclassinheritsthemenubehaviors.
Ifyouwanttoaddmenuitemstooneofyourdecendentactivities,overrideonCreateOptionsMenu()inthatActivity.Callsuper.onCreateOptionsMenu(menu)sotheoriginalmenuitemsarecreated,thenaddnewmenuitemswithmenu.add().Youcanalsooverridethesuperclass'sbehaviorforindividualmenuitems.
Changingthemenuwhenitopens
TheonCreateOptionsMenu()methodiscalledonlythefirsttimetheOptionsMenuisopened.Thesystemkeepsandre-usestheMenuyoudefineinthismethoduntilyourActivityisdestroyed.IfyouwanttochangetheOptionsMenueachtimeitopens,youmustoverridetheonPrepareOptionsMenu()method.ThispassesyoutheMenuobjectasitcurrentlyexists.Thisisusefulifyou'dliketoremove,add,disable,orenablemenuitemsdependingonthecurrentstateofyourapplication.
Note:
YoushouldneverchangeitemsintheOptionsMenubasedontheViewcurrentlyinfocus.Whenintouchmode(whentheuserisnotusingatrackballord-pad),Viewscannottakefocus,soyoushouldneverusefocusasthebasisformodifyingitemsintheOptionsMenu.Ifyouwanttoprovidemenuitemsthatarecontext-sensitivetoaView,useaContextMenu.
CreatingaContextMenu
Acontextmenuisconceptuallysimilartothemenudisplayedwhentheuserperformsa"right-click"onaPC.Youshoulduseacontextmenutoprovidetheuseraccesstoactionsthatpertaintoaspecificitemintheuserinterface.OnAndroid,acontextmenuisdisplayedwhentheuserperformsa"longpress"(pressandhold)onanitem.
YoucancreateacontextmenuforanyView,thoughcontextmenusaremostoftenusedforitemsinaListView.Whentheuserperformsalong-pressonaniteminaListViewandthelistisregisteredtoprovideacontextmenu,thelistitemsignalstotheuserthatacontextmenuisavailablebyanimatingitsbackgroundcolor—ittransitionsfromorangetowhitebeforeopeningthecontextmenu.(TheContactsapplicationdemonstratesthisfeature.)
RegisteraListView
IfyourActivityusesaListViewandyouwantalllistitemstoprovideacontextmenu,registerallitemsforacontextmenubypassingtheListViewtoregisterForContextMenu().Forexample,ifyou'reusingaListActivity,registeralllistitemslikethis:
registerForContextMenu(getListView());
InorderforaViewtoprovideacontextmenu,youmust"register"theviewforacontextmenu.CallregisterForContextMenu()andpassittheViewyouwanttogiveacontextmenu.WhenthisViewthenreceivesalong-press,itdisplaysacontextmenu.
Todefinethecontextmenu'sappearanceandbehavior,overrideyourActivity'scontextmenucallbackmethods,onCreateContextMenu()andonContextItemSelected().
Forexample,here'sanonCreateContextMenu()thatusesthecontext_menu.xmlmenuresource:
@Override
publicvoidonCreateContextMenu(ContextMenumenu,Viewv,
ContextMenuInfomenuInfo){
super.onCreateContextMenu(menu,v,menuInfo);
MenuInflaterinflater=getMenuInflater();
inflater.inflate(R.menu.context_menu,menu);
}
MenuInflaterisusedtoinflatethecontextmenuf