Вы находитесь на странице: 1из 13

9/27/2011

1
8
Android
UsingMenus
VictorMatos
ClevelandStateUniversity
Notesarebasedon:
Th B C d ' G id t A d id D l t The Busy Coder's Guide to Android Development
by Mark L.Murphy
Copyright 20082009CommonsWare,LLC.
ISBN:9780981678009
&
Android Developers
http://developer.android.com/index.html
8.Android UI UsingMenus
UsingMenus
Menususuallyincreasethefunctionalityofanappby
providingadditionaloperationsonasmalloverlapping
panel panel.
Androidprovidestwotypesofmenuknownas:
optionsmenu andcontextmenu.
1. The options menu is triggered by pressing the
22
1. Theoptionsmenuistriggeredbypressingthe
hardwareMenu buttononthedevice,while
2. thecontextmenuisraisedbyatapandholdonthe
widgetassociatedtothemenu.
9/27/2011
2
8.Android UI UsingMenus
UsingMenus
Example:Usinganoptionmenu
Options
availablein
thiscontext
33
PressMenu
button
Amaxofsixentriesper
menu.Excesswillbedisplayed
aspartoftheMore option
8.Android UI UsingMenus
UsingMenus
Example:
Usinganoptionmenu
Fiveavailable
Optionsin
thi t t
44
PressMenu
button
thiscontext
9/27/2011
3
8.Android UI UsingMenus
UsingMenus
Example:
DealingwithSMS
(textmessages)by
Available
( g ) y
usingthebuiltin
Messaging apps
contextmenu
Available
options
55
Tap&Hold
8.Android UI UsingMenus
UsingMenus
Observation:
Option andContext Menusmayinclude: p y
1. Text
2. Icons
3. RadioButtons
4. CheckBoxes
5. Submenus
66
6. Shortcutkeys
9/27/2011
4
8.Android UI UsingMenus
UsingMenus
Example1:UsinganOptionMenu
Inthisapplicationthe
Optionmenuoffers
awayofchangingthe
textsize(onboth
EditText boxes)
77
ClickonMenu
buttontosee
sizeoptions
Afterchoosingoption:
50points
8.Android UI UsingMenus
UsingMenus
Example1:UsinganOptionMenu
Uptosixoptionswill
Bedisplayedonthe
Optionmenu.
Iftherearemorethan
sixoptionspushing
theMorebuttonwill
showtherest
88
ClicktheMorebuttontosee
additionaloptions
Additionalchoicesof
theOptionmenu
9/27/2011
5
8.Android UI UsingMenus
UsingMenus
Example1:UsingaContextMenu
Eachviewcouldhaveanassociated
ContextMenu
Longpressa
textboxto
invokeits
ContextMenu
99
8.Android UI UsingMenus
UsingMenus
Example1:UsingOptionandContextMenu
Theappshowstwotextboxes.Menusareusedtochangetextssize,color,andstyle.
<?xml ver si on="1.0" encoding="utf-8"?>
<Li near Layout xml ns: andr oi d="http://schemas.android.com/apk/res/android"
andr oi d: or i ent at i on="vertical"
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="fill_parent" >
<Edi t Text
andr oi d: i d="@+id/etMessage1"
andr oi d: t ext ="Hello world"
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="wrap_content"
andr oi d: l ayout _mar gi n = "5dp" />
<Edi t Text
andr oi d: i d="@+id/etMessage2"
andr oi d: t ext ="Hola mundo"
10 10
andr oi d: t ext Hola mundo
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="wrap_content"
andr oi d: l ayout _mar gi n = "5dp" />
<Text Vi ew
andr oi d: t ext ="Press the MENU key, or \nLong-press text-boxes"
andr oi d: l ayout _wi dt h="wrap_content"
andr oi d: l ayout _hei ght ="wrap_content"
andr oi d: l ayout _gr avi t y="center" />
</ Li near Layout >
9/27/2011
6
8.Android UI UsingMenus
UsingMenus
Example1:UsingOptionandContextMenu
Theappshowstwotextboxes.Menusareusedtochangetextssize,color,andstyle.
package cis493.matos.menu;
/ / usi ng Menus ( Opt i on & Cont ext )
import android.app.Activity; import android.app.Activity;
public class Menu1Act1 extends Activity {
Edi t Text et Message1;
Edi t Text et Message2;
I nt eger [ ] ar r ayPoi nt Si ze = {10, 20, 30, 40, 50};
@Over r i de
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
set Cont ent Vi ew( R. l ayout . main);
t M 1 ( Edi t T t ) f i dVi B I d( R i d tM 1)
11 11
et Message1 = ( Edi t Text ) f i ndVi ewByI d( R. i d. etMessage1);
et Message2 = ( Edi t Text ) f i ndVi ewByI d( R. i d. etMessage2);
/ / you may r egi st er an i ndi vi dual cont ext menu f or each vi ew
r egi st er For Cont ext Menu( et Message1) ;
r egi st er For Cont ext Menu( et Message2) ;
} / / onCr eat e
8.Android UI UsingMenus
UsingMenus
Example1:UsingOptionandContextMenu
Theappshowstwotextboxes.Menusareusedtochangetextssize,color,andstyle.
/ / set t he opt i on menu f or t he cur r ent act i vi t y
@Over r i de
public boolean onCreateOptionsMenu(Menu menu) { public boolean onCreateOptionsMenu(Menu menu) {
/ / onl y one Opt i on menu per act i vi t y
popul at eMyFi r st Menu( menu) ;
return super.onCreateOptionsMenu(menu);
}
/ / det ect what vi ew i s cal l i ng and cr eat e i t s cont ext menu
@Over r i de
public void onCreateContextMenu(ContextMenu menu, View v,
Cont ext MenuI nf o menuI nf o) {
super.onCreateContextMenu(menu, v, menuInfo);
/ / d i d h t t t d t b d
12 12
/ / deci de what cont ext menu needs t o be made
if (v.getId() == etMessage1.getId())
/ / cr eat e a menu f or et Message1 box
popul at eMyFi r st Menu( menu) ;
if (v.getId() == etMessage2.getId()){
/ / cr eat e a menu f or et Message2 box
popul at eMySecondMenu( menu) ;
}
} / / onCr eat eCont ext Menu
9/27/2011
7
8.Android UI UsingMenus
UsingMenus
Example1:UsingOptionandContextMenu
Theappshowstwotextboxes.Menusareusedtochangetextssize,color,andstyle.
private void populateMyFirstMenu(Menu menu){
int groupId = 0;
/ / ar gument s: gr oupI d, opt i onI d, or der , t i t l e / / ar gument s: gr oupI d, opt i onI d, or der , t i t l e
menu. add( gr oupI d, 1, 1, "10 poi nt s") ;
menu. add( gr oupI d, 2, 2, "20 poi nt s") ;
menu. add( gr oupI d, 3, 3, "30 poi nt s") ;
menu. add( gr oupI d, 4, 4, "40 poi nt s") ;
menu. add( gr oupI d, 5, 5, "50 poi nt s") ;
menu. add( gr oupI d, 6, 8, "Red t ext " ) ;
menu. add( gr oupI d, 7, 7, "Gr een Text " ) ;
menu. add( gr oupI d, 8, 6, "Bl ue t ext ") ;
} / / popul at eMyMenu
13 13
private void populateMySecondMenu(Menu menu){
int groupId = 0;
/ / ar gument s: gr oupI d, opt i onI d, or der , t i t l e
menu. add( gr oupI d, 9, 1, " Bol d" ) ;
menu. add( gr oupI d, 10, 2, " I t al i c" ) ;
menu. add( gr oupI d, 11, 3, " Nor mal " ) ;
}/ / popul at eMySecondMenu
8.Android UI UsingMenus
UsingMenus
Example1:UsingOptionandContextMenu
Theappshowstwotextboxes.Menusareusedtochangetextssize,color,andstyle.
/ / cal l ed whenever an i t emi n your cont ext menu i s sel ect ed
@Over r i de @Over r i de
public boolean onContextItemSelected(MenuItem item) {
return(applyMenuOption(item) ||
super.onContextItemSelected(item) );
}
/ / cal l ed whenever an i t emi n your opt i ons menu i s sel ect ed
@Over r i de
public boolean onOptionsItemSelected(MenuItem item) {
return(applyMenuOption(item) ||
s per onOptionsItemSelected(item) )
14 14
super.onOptionsItemSelected(item) );
}
Note:boolean eventobserversofthetypeonEvent(...)byconventionreturn
true toindicatethetriggeredeventhasbeenconsumedbythemethod,when
false isreturnedtheeventisstillaliveandcouldbeconsumedbyothers.
9/27/2011
8
8.Android UI UsingMenus
UsingMenus
Example1:UsingOptionandContextMenu
/ / appl y t he act i on associ at ed t o sel ect ed i t em
private boolean applyMenuOption(MenuItem item){
int menuItemId = item.getItemId(); // 1, 2, 3, ...11
St r i ng st r Msg2 = et Message2. get Text ( ) . t oSt r i ng( ) ;
if (menuItemId <= 5) {
/ / f i r st f i ve opt i on ar e f or set t i ng t ext si ze
int newPointSize = arrayPointSize[menuItemId - 1];
et Message1. set Text Si ze( newPoi nt Si ze) ;
et Message2. set Text Si ze( newPoi nt Si ze) ;
}
else {
/ / ei t her change col or on box t ext 1 or st yl e on t ext 2
if (menuItemId == 6)
et Message1. set Text Col or ( Color.RED);
/ / et Message1. set Text Col or ( 0xf f f f 0000) ; / / r ed
else if (menuItemId == 7)
15 15
et Message1. set Text Col or ( 0xf f 00f f 00) ; / / gr een
else if (menuItemId == 8)
et Message1. set Text Col or ( 0xf f 0000f f ) ; / / bl ue
else if (menuItemId == 9)
et Message2. set Text ( beaut i f y( st r Msg2, " BOLD" ) ) ; / / bol d
else if (menuItemId == 10)
et Message2. set Text ( beaut i f y( st r Msg2, " I TALI C" ) ) ; / / i t al i c
else if (menuItemId == 11)
et Message2. set Text ( beaut i f y( st r Msg2, " NORMAL" ) ) ; / / nor mal
}
return false;
} / / appl yMenuOpt i on
8.Android UI UsingMenus
UsingMenus
Example1:UsingOptionandContextMenu
Theappshowstwotextboxes.Menusareusedtochangetextssize,color,andstyle.
/ / changi ng t ext st yl e usi ng HTML f or mat t i ng
/ / Spanned i s t ext t o whi ch you coul d add f or mat t i ng f eat ur es
private Spanned beautify (String originalText, String selectedStyle){
Spanned answer = null;
if (selectedStyle.equals("BOLD"))
answer = Ht ml . fromHtml("<b>" + originalText +"</b");
else if (selectedStyle.equals("ITALIC"))
answer = Ht ml . fromHtml("<i>" + originalText +"</i>");
else if (selectedStyle.equals("NORMAL"))
answer = Ht ml . fromHtml("<normal>" + originalText +"</normal");
return answer;
} / / b t i f
16 16
} / / beaut i f y
} / / Menu1Act 1
9/27/2011
9
8.Android UI UsingMenus
UsingMenus
CommentsonCreatinganOption&ContextMenu
Step1.
Indicatewhichwidget(s)onyouractivityhavecontextmenus.Todothis,call Indicatewhichwidget(s)onyouractivityhavecontextmenus.Todothis,call
registerForContextMenu(theWidget)
supplyingtheViewthatisthewidgetneedingacontextmenu.
Step2.
ImplementonCreateContextMenu(),populateyourmenuaddingtext,icons,etc.to
thedifferentoptions. Useinputmenu parametertodeterminewhichmenutobuild
(assumingyouractivityhasmorethanone).
17 17 17
TheonCreateContextMenu() methodgetstheContextMenu itself,theView the
contextmenuisassociatedwith,andaContextMenu.ContextMenuInfo,which
tellsyouwhichiteminthelisttheuserdidthetapandholdover,incase
youwanttocustomizethecontextmenubasedonthatinformation
8.Android UI UsingMenus
UsingMenus
CommentsonCreatinganOption&ContextMenu
onCreateContextMenu() iscalledeachtimethecontextmenu
i t d isrequested.
Unliketheoptionsmenu(whichisonlybuiltonceper
activity),contextmenusarediscardedoncetheyareusedor
dismissed.
To find out when a context menu choice was chosen
18 18 18
Tofindoutwhenacontextmenuchoicewaschosen,
implementonContextItemSelected() ontheactivity.
9/27/2011
10
8.Android UI UsingMenus
UsingMenus
CommentsonCreatinganOption&ContextMenu
InExample1theeventobservers:
onOptionsItemSelected() (foroptionsmenuselections)and onOptionsItemSelected() (foroptionsmenuselections)and
onContextItemSelected() (forcontextmenuselections)
delegateontheapplyMenuChoice()methodtheperformingoftheactions
associatedtothechoicesmadebytheuser.
@Over r i de
public boolean onOptionsItemSelected(MenuItem item) {
return (applyMenuChoice(item) );
}
19 19 19
}
@Over r i de
public boolean onContextItemSelected(MenuItem item) {
return (applyMenuChoice(item));
}
8.Android UI UsingMenus
UsingMenus
Example2:EnhancingOption/ContextMenu
Thisextensionofthe
previousexampleadds
ExtendingExample1.
icons andlinks tothe
OptionMenuentries,
aswellasasubmenu
listtiedtoonethe
optionmenubuttons.
Keyboardshortcuts/links
20 20
ClickonSubMenu tosee
additionaloptions
9/27/2011
11
8.Android UI UsingMenus
UsingMenus
Example2:EnhancingOption/ContextMenu
Thisextensionofthe
previousexampleadds
ExtendingExample1.
icons andlinks tothe
OptionMenuentries,
aswellasasubmenu
listtiedtoonethe
optionmenubuttons.
21 21
8.Android UI UsingMenus
UsingMenus
Example2:EnhancingOption/ContextMenu
private void populateMyFirstMenu(Menu menu){
int groupId = 0;
/ / ar gument s: gr oupI d, opt i onI d, or der , t i t l e
ExtendingExample1.
Replacethemethod
populateMyFirstMenu
withthefollowingcode
MenuI t emi t em1 = menu. add( gr oupI d, 1, 1, " 10 poi nt s" ) ;
MenuI t emi t em2 = menu. add( gr oupI d, 2, 2, " 20 poi nt s" ) ;
MenuI t emi t em3 = menu. add( gr oupI d, 3, 3, " 30 poi nt s" ) ;
MenuI t emi t em4 = menu. add( gr oupI d, 4, 4, " 40 poi nt s" ) ;
/ / MenuI t emi t em5 = menu. add( gr oupI d, 5, 5, " 50 poi nt s" ) ;
MenuI t emi t em6 = menu. add( gr oupI d, 6, 8, " Red t ext " ) ;
MenuI t emi t em7 = menu. add( gr oupI d, 7, 7, " Gr een Text " ) ;
MenuI t emi t em8 = menu. add( gr oupI d, 8, 6, " Bl ue t ext " ) ;
/ / set i cons
i t em1. set I con( R. dr awabl e. uno);
i t em2 set I con( R dr awabl e dos);
Figuresusedinthisexampleweretakenfrom:
C:\androidsdkwindows\platforms\android4\data\res\drawable
emo_im_cool.png,emo_im_laughing.png,...
Removethislinefrom
previousversion
22 22
i t em2. set I con( R. dr awabl e. dos);
i t em3. set I con( R. dr awabl e. tres);
i t em4. set I con( R. dr awabl e. cuatro);
/ / shor t cut s usi ng devi ce s keyboar d- keypad
/ / on a G1 sl i de t o open t he keyboar d and
/ / t ype di gi t 1( same as cont ext menu UNO)
i t em1. set Shor t cut ( ' 1' , ' 1' ) ;
i t em2. set Shor t cut ( ' 2' , ' 2' ) ;
i t em3. set Shor t cut ( ' 3' , ' 3' ) ;
i t em4. set Shor t cut ( ' 4' , ' 4' ) ;
_ _ p g _ _ g g p g
9/27/2011
12
8.Android UI UsingMenus
UsingMenus
Example2:EnhancingOption/ContextMenu
/ / addi ng a sub- menu as f i f t h ent r y of t hi s menu
/ / . addSubMenu( i nt gr oupI d, i nt i t emI d, i nt or der , Char Sequence t i t l e)
ExtendingExample1.
Continuation
Replacethemethod
populateMyFirstMenu
withthefollowingcode
int smGroupId = 0; // don't care, same as Menu.NONE
int smItemId = 5; // fifth element
int smOrder = 5; // don't care, same as Menu.NONE
SubMenu mySubMenu5 = menu. addSubMenu( smGr oupI d, smI t emI d, smOr der , " Sub- Menu- CI NCO" ) ;
mySubMenu5. set Header I con( R. dr awabl e. btn_rating_star_on_pressed);
mySubMenu5. set I con( R. dr awabl e. cinco);
/ / . add( i nt gr oupI d, i nt i t emI d, i nt or der , Char Sequence t i t l e)
MenuI t emsub51 = mySubMenu5. add( smGr oupI d, 5, 1, " Sub Menu 5- 1" ) ;
MenuI t emsub52 = mySubMenu5. add( smGr oupI d, 5, 2, " Sub Menu 5- 2" ) ;
MenuI t emsub53 = mySubMenu5. add( smGr oupI d, 5, 3, " Sub Menu 5- 3" ) ;
23 23
} / / popul at eMyFi r st Menu
8.Android UI UsingMenus
UsingMenus
Example2:EnhancingOption/ContextMenu
private boolean applyMenuOption(MenuItem item){
int menuItemId = item.getItemId(); //1, 2, 3, ...11
ExtendingExample1.
Continuation
Replacethemethod
applyMenuOption
withthefollowingcode
int menuItemId item.getItemId(); //1, 2, 3, ...11
St r i ng st r Msg2 = et Message2. get Text ( ) . t oSt r i ng( ) ;
if (menuItemId < 5) {
/ / f i r st f our opt i ons ar e f or set t i ng t ext si ze
int newPointSize = arrayPointSize[menuItemId - 1];
et Message1. set Text Si ze( newPoi nt Si ze) ;
et Message2. set Text Si ze( newPoi nt Si ze) ;
}
else if (menuItemId == 5) {
/ / t h b ( t t h d t 5t h i t ) i d h
Sameas
before
Takecareof
submenuhere
24 24
/ / t he sub- menu ( at t ached t o 5t h i t em) i s pr ocessed her e
et Message1. set Text (
" You have sel ect ed: \ n" +i t em. get Ti t l e( )
+ " \ nI d: " + menuI t emI d
+ " or der : " + i t em. get Or der ( ) ) ;
}
/ / ei t her change col or on t ext 1 or st yl e on t ext 2
else if (menuItemId == 6)
et Message1. set Text Col or ( 0xf f f f 0000) ; / / r ed
9/27/2011
13
8.Android UI UsingMenus
UsingMenus
Example2:EnhancingOption/ContextMenu
else if (menuItemId == 7)
et Message1. set Text Col or ( 0xf f 00f f 00) ; / / gr een
else if (menuItemId == 8)
ExtendingExample1.
Continuation
Replacethemethod
applyMenuOption
withthefollowingcode
Same as else if (menuItemId 8)
et Message1. set Text Col or ( 0xf f 0000f f ) ; / / bl ue
else if (menuItemId == 9)
et Message2. set Text ( beaut i f y( st r Msg2, " BOLD" ) ) ; / / bol d
else if (menuItemId == 10)
et Message2. set Text ( beaut i f y( st r Msg2, " I TALI C" ) ) ; / / i t al i c
else if (menuItemId == 11)
et Message2. set Text ( beaut i f y( st r Msg2, " NORMAL" ) ) ; / / nor mal
return false;
} / / l M O t i
Sameas
before
25 25
} / / appl yMenuOpt i on
8.Android UI UsingMenus
UsingMenus
Questions?
26 26 26

Вам также может понравиться