Creating Menus.docx

上传人:b****9 文档编号:25414017 上传时间:2023-06-08 格式:DOCX 页数:14 大小:70.34KB
下载 相关 举报
Creating Menus.docx_第1页
第1页 / 共14页
Creating Menus.docx_第2页
第2页 / 共14页
Creating Menus.docx_第3页
第3页 / 共14页
Creating Menus.docx_第4页
第4页 / 共14页
Creating Menus.docx_第5页
第5页 / 共14页
点击查看更多>>
下载资源
资源描述

Creating Menus.docx

《Creating Menus.docx》由会员分享,可在线阅读,更多相关《Creating Menus.docx(14页珍藏版)》请在冰豆网上搜索。

Creating Menus.docx

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:

CreatesaMenu,whichisacontainerformenuitems.Itmustbetherootnodeandholdsoneormoreofthefollowingelements.Youcanalsonestthiselementinantocreateasubmenu.

CreatesaMenuItem,whichrepresentsasingleiteminamenu.

Anoptional,invisiblecontainerforelements.Itallowsyoutocategorizemenuitemssotheysharepropertiessuchasactivestateandvisibility.SeeMenugroups.

Forexample,hereisafileinres/menu/namedgame_menu.xml:

xmlversion="1.0"encoding="utf-8"?

>

android="

  

id="@+id/new_game"

     android:

icon="@drawable/ic_new_game"

     android:

title="@string/new_game"/>

  

id="@+id/quit"

     android:

icon="@drawable/ic_quit"

     android:

title="@string/quit"/>

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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 人文社科 > 教育学心理学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1