SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Downloaden Sie, um offline zu lesen
Android UI - Menus
Topics
• Types of menus
• Options menu
• Context menu
• Submenu
• Creating menu using Menu resource
Types of Menus
Types of Menus
• Context menu
> Floating list of menu items that may appear when
you perform a long-press on a View
• Options menu
> Revealed when the device MENU key is pressed
• Submenu
> Used to organize menu items into groups
> A Submenu item does not support nested Submenus
Context Menu
Context Menu
• Context menus do
not support item
shortcuts and item
icons.
How to Create Context Menu?
• When Context menu is opened for the first
time, the Android system will call the Activity's
onCreateContextMenu(Menu menu) callback
method.
> Override this method in your Activity class and
populate the Menu object given to you with
MenuItem's.
• You can populate the menu in two ways
> Scheme #1: by calling add() for each item you'd like
in the menu.
> Scheme #2: by inflating a menu resource that was
defined in XML (preferred)
Populating Menu with Menu Items: #1
// Override this method of Activity class in order to create menu items.
@Override
public void onCreateContextMenu(
ContextMenu menu, // Context menu that is being built
View view, // The view for which the context menu is being built
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderTitle("Context menu");
menu.add(0, Menu.FIRST, Menu.NONE, "menu #1");
menu.add(0, Menu.FIRST + 1, Menu.NONE, "menu #2");
menu.add(0, Menu.FIRST + 2, Menu.NONE, "menu #3");
menu.add(0, Menu.FIRST + 3, Menu.NONE, "menu #4");
}
How to handle Menu Selection?
• When a menu item is selected from the Context
Menu, onContextItemSelected() callback
method of your Activity gets called
> This callback passes you the MenuItem that has been
selected.
> You can identify the item by requesting the itemId,
with getItemId(), which returns the integer that was
assigned with the add() method.
> Once you identify the menu item, you can take an
appropriate action.
Example: Handling Menu Selection
/* Handles item selections */
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_NEW_GAME:
newGame();
return true;
case MENU_QUIT:
quit();
return true;
}
return false;
}
Options Menu
When to use Options Menu?
• The Options Menu is
where you should
include basic
application functions
and any necessary
navigation items
(e.g., to a home
screen or application
settings).
How Options Menu Work?
• 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.
Populating Menu with Menu Items: #1
/* Creates the menu items without Icons */
public boolean onCreateOptionsMenu(Menu menu) {
// The add() method used in this sample takes four arguments:
// groupId, itemId, order, and title.
menu.add(0, MENU_NEW_GAME, 0, "New Game");
menu.add(0, MENU_QUIT, 0, "Quit");
return true;
}
/* Creates the menu items with Icons. Note that add() method returns
newly created MenuItem object to set additional properties like an icon,
a keyboard shortcut, an intent, and other settings for the item. */
public boolean onCreateOptionsMenu(Menu menu) {
// The add() method used in this sample takes four arguments:
// groupId, itemId, order, and title.
menu.add(0, MENU_NEW_GAME, 0,
"New Game").setIcon(R.drawable.menu_new_game_icon);
menu.add(0, MENU_QUIT, 0, "Quit").setIcon(R.drawable.menu_quit_icon);
return true;
}
How to handle Menu Selection?
• When a menu item is selected from the Options
Menu, onOptionsItemSelected() callback
method of your Activity gets called
> This callback passes you the MenuItem that has been
selected.
> You can identify the item by requesting the itemId,
with getItemId(), which returns the integer that was
assigned with the add() method.
> Once you identify the menu item, you can take an
appropriate action.
Example: Handling Menu Selection
/* Handles item selections */
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_NEW_GAME:
newGame();
return true;
case MENU_QUIT:
quit();
return true;
}
return false;
}
Submenu
When to use SubMenu?
• If you have several menu items that can be
grouped together with a title, consider
organizing them into a Submenu.
Example: Creating Submenu
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
// Create submenu "File"
SubMenu fileMenu = menu.addSubMenu("File");
fileMenu.add("New");
fileMenu.add("Open File");
fileMenu.add("Close");
fileMenu.add("Close All");
// Create submenu "Edit"
SubMenu editMenu = menu.addSubMenu("Edit");
editMenu.add("Undo Typing");
editMenu.add("Redo");
editMenu.add("Cut");
return result;
}
Creating Menu using
Menu Resource
Why using Menu Resource?
• Instead of instantiating Menu objects in your
application code, you should define a menu and
all its items in an XML menu resource, then
inflate the menu resource (load it as a
programmable object) in your application code.
• Defining your menus in XML is a better practice
(than creating them in code) because it
separates your interface design from your
application code (the same as when you define
your Activity layout in XML).
When to Use Menu Resource File?
• Create <menu_resource>.xml under res/menu/
directory
• Inflate the Menu Resource file using
inflate(<menu-resource-id>) method of the
MenuInflator class
> Menu objects are created from the Menu resource
file
Example: Inflating Menu Resource
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu XML resource.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.title_only, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.jump:
Toast.makeText(this, "Jump up in the air!", Toast.LENGTH_LONG)
.show();
return true;
case R.id.dive:
Toast.makeText(this, "Dive into the water!", Toast.LENGTH_LONG)
.show();
return true;
}
Example: Menu Resource File
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/jump"
android:title="Jump!"
android:icon="@drawable/draw_jump" />
<item android:id="@+id/dive"
android:title="Dive!"
android:icon="@drawable/draw_dive" />
</menu>
Thank you

Weitere ähnliche Inhalte

Was ist angesagt?

Day 4: Android: UI Widgets
Day 4: Android: UI WidgetsDay 4: Android: UI Widgets
Day 4: Android: UI Widgets
Ahsanul Karim
 
android activity
android activityandroid activity
android activity
Deepa Rani
 
Ch 3 event driven programming
Ch 3 event driven programmingCh 3 event driven programming
Ch 3 event driven programming
Chaffey College
 
android-tutorial-for-beginner
android-tutorial-for-beginnerandroid-tutorial-for-beginner
android-tutorial-for-beginner
Ajailal Parackal
 

Was ist angesagt? (20)

Android Fragment
Android FragmentAndroid Fragment
Android Fragment
 
Day 4: Android: UI Widgets
Day 4: Android: UI WidgetsDay 4: Android: UI Widgets
Day 4: Android: UI Widgets
 
Android studio
Android studioAndroid studio
Android studio
 
Activities, Fragments, and Events
Activities, Fragments, and EventsActivities, Fragments, and Events
Activities, Fragments, and Events
 
android activity
android activityandroid activity
android activity
 
Junit
JunitJunit
Junit
 
androidstudio.pptx
androidstudio.pptxandroidstudio.pptx
androidstudio.pptx
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android Fragments
 
Ch 3 event driven programming
Ch 3 event driven programmingCh 3 event driven programming
Ch 3 event driven programming
 
Android User Interface
Android User InterfaceAndroid User Interface
Android User Interface
 
Android studio installation
Android studio installationAndroid studio installation
Android studio installation
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android Development
 
AndroidManifest
AndroidManifestAndroidManifest
AndroidManifest
 
Introduction to android
Introduction to androidIntroduction to android
Introduction to android
 
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
Android | Android Activity Launch Modes and Tasks | Gonçalo SilvaAndroid | Android Activity Launch Modes and Tasks | Gonçalo Silva
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
 
Android application development ppt
Android application development pptAndroid application development ppt
Android application development ppt
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
android-tutorial-for-beginner
android-tutorial-for-beginnerandroid-tutorial-for-beginner
android-tutorial-for-beginner
 
Android intents
Android intentsAndroid intents
Android intents
 

Andere mochten auch

Android location
Android locationAndroid location
Android location
Krazy Koder
 
Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]
Nehil Jain
 
Android appwidget
Android appwidgetAndroid appwidget
Android appwidget
Krazy Koder
 
Android ui dialog
Android ui dialogAndroid ui dialog
Android ui dialog
Krazy Koder
 
Android notification
Android notificationAndroid notification
Android notification
Krazy Koder
 

Andere mochten auch (20)

android menus
android menusandroid menus
android menus
 
Menu in android
Menu in androidMenu in android
Menu in android
 
Action Bar and Menu
Action Bar and MenuAction Bar and Menu
Action Bar and Menu
 
Action Bar in Android
Action Bar in AndroidAction Bar in Android
Action Bar in Android
 
04 user interfaces
04 user interfaces04 user interfaces
04 user interfaces
 
Android in practice
Android in practiceAndroid in practice
Android in practice
 
Android Training - Sliding Menu
Android Training - Sliding MenuAndroid Training - Sliding Menu
Android Training - Sliding Menu
 
Android location
Android locationAndroid location
Android location
 
Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]
 
Android appwidget
Android appwidgetAndroid appwidget
Android appwidget
 
Android Notifications in Android Nougat 7.0
Android Notifications in Android Nougat 7.0Android Notifications in Android Nougat 7.0
Android Notifications in Android Nougat 7.0
 
Android L04 - Notifications and Threading
Android L04 - Notifications and ThreadingAndroid L04 - Notifications and Threading
Android L04 - Notifications and Threading
 
2310 b xd
2310 b xd2310 b xd
2310 b xd
 
Android ui dialog
Android ui dialogAndroid ui dialog
Android ui dialog
 
Alertdialog in android
Alertdialog in androidAlertdialog in android
Alertdialog in android
 
Android UI Development
Android UI DevelopmentAndroid UI Development
Android UI Development
 
Android App Development - 06 Fragments
Android App Development - 06 FragmentsAndroid App Development - 06 Fragments
Android App Development - 06 Fragments
 
Android Location and Maps
Android Location and MapsAndroid Location and Maps
Android Location and Maps
 
Android notification
Android notificationAndroid notification
Android notification
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 

Ähnlich wie Android ui menu

1 PROBLEM You are to design and implement a Menu class.docx
1 PROBLEM You are to design and implement a Menu class.docx1 PROBLEM You are to design and implement a Menu class.docx
1 PROBLEM You are to design and implement a Menu class.docx
honey725342
 
Menu bars and menus
Menu bars and menusMenu bars and menus
Menu bars and menus
myrajendra
 
Day 5: Android User Interface [View Widgets]
Day 5: Android User Interface [View Widgets]Day 5: Android User Interface [View Widgets]
Day 5: Android User Interface [View Widgets]
Ahsanul Karim
 

Ähnlich wie Android ui menu (20)

1 PROBLEM You are to design and implement a Menu class.docx
1 PROBLEM You are to design and implement a Menu class.docx1 PROBLEM You are to design and implement a Menu class.docx
1 PROBLEM You are to design and implement a Menu class.docx
 
Intake 37 8
Intake 37 8Intake 37 8
Intake 37 8
 
Android Lab Test : Creating a menu dynamically (english)
Android Lab Test : Creating a menu dynamically (english)Android Lab Test : Creating a menu dynamically (english)
Android Lab Test : Creating a menu dynamically (english)
 
Intake 38 8
Intake 38 8Intake 38 8
Intake 38 8
 
Android session 3
Android session 3Android session 3
Android session 3
 
Menu stripe
Menu stripeMenu stripe
Menu stripe
 
MenusAnddailogsinandroidddfdadusjsjdjdjs
MenusAnddailogsinandroidddfdadusjsjdjdjsMenusAnddailogsinandroidddfdadusjsjdjdjs
MenusAnddailogsinandroidddfdadusjsjdjdjs
 
Chapt 04 user interaction
Chapt 04 user interactionChapt 04 user interaction
Chapt 04 user interaction
 
01 10 - graphical user interface - others
01  10 - graphical user interface - others01  10 - graphical user interface - others
01 10 - graphical user interface - others
 
Menu bars and menus
Menu bars and menusMenu bars and menus
Menu bars and menus
 
Google calendar integration in iOS app
Google calendar integration in iOS appGoogle calendar integration in iOS app
Google calendar integration in iOS app
 
360 Flex Atlanta
360 Flex Atlanta360 Flex Atlanta
360 Flex Atlanta
 
Android Lab Test : Creating a menu context (english)
Android Lab Test : Creating a menu context (english)Android Lab Test : Creating a menu context (english)
Android Lab Test : Creating a menu context (english)
 
Lesson 9
Lesson 9Lesson 9
Lesson 9
 
Day 5: Android User Interface [View Widgets]
Day 5: Android User Interface [View Widgets]Day 5: Android User Interface [View Widgets]
Day 5: Android User Interface [View Widgets]
 
lec 9.pptx
lec 9.pptxlec 9.pptx
lec 9.pptx
 
Android menus in android-chapter15
Android menus in android-chapter15Android menus in android-chapter15
Android menus in android-chapter15
 
Lab3-Android
Lab3-AndroidLab3-Android
Lab3-Android
 
Lab1-android
Lab1-androidLab1-android
Lab1-android
 
Aula 6 - 08/05 (Menu)
Aula 6 - 08/05 (Menu)Aula 6 - 08/05 (Menu)
Aula 6 - 08/05 (Menu)
 

Mehr von Krazy Koder (20)

2310 b xd
2310 b xd2310 b xd
2310 b xd
 
2310 b xd
2310 b xd2310 b xd
2310 b xd
 
2310 b xc
2310 b xc2310 b xc
2310 b xc
 
2310 b xb
2310 b xb2310 b xb
2310 b xb
 
2310 b 17
2310 b 172310 b 17
2310 b 17
 
2310 b 16
2310 b 162310 b 16
2310 b 16
 
2310 b 16
2310 b 162310 b 16
2310 b 16
 
2310 b 15
2310 b 152310 b 15
2310 b 15
 
2310 b 15
2310 b 152310 b 15
2310 b 15
 
2310 b 14
2310 b 142310 b 14
2310 b 14
 
2310 b 13
2310 b 132310 b 13
2310 b 13
 
2310 b 12
2310 b 122310 b 12
2310 b 12
 
2310 b 11
2310 b 112310 b 11
2310 b 11
 
2310 b 10
2310 b 102310 b 10
2310 b 10
 
2310 b 09
2310 b 092310 b 09
2310 b 09
 
2310 b 08
2310 b 082310 b 08
2310 b 08
 
2310 b 08
2310 b 082310 b 08
2310 b 08
 
2310 b 08
2310 b 082310 b 08
2310 b 08
 
2310 b 07
2310 b 072310 b 07
2310 b 07
 
2310 b 06
2310 b 062310 b 06
2310 b 06
 

Kürzlich hochgeladen

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Kürzlich hochgeladen (20)

psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 

Android ui menu

  • 1. Android UI - Menus
  • 2. Topics • Types of menus • Options menu • Context menu • Submenu • Creating menu using Menu resource
  • 4. Types of Menus • Context menu > Floating list of menu items that may appear when you perform a long-press on a View • Options menu > Revealed when the device MENU key is pressed • Submenu > Used to organize menu items into groups > A Submenu item does not support nested Submenus
  • 6. Context Menu • Context menus do not support item shortcuts and item icons.
  • 7. How to Create Context Menu? • When Context menu is opened for the first time, the Android system will call the Activity's onCreateContextMenu(Menu menu) callback method. > Override this method in your Activity class and populate the Menu object given to you with MenuItem's. • You can populate the menu in two ways > Scheme #1: by calling add() for each item you'd like in the menu. > Scheme #2: by inflating a menu resource that was defined in XML (preferred)
  • 8. Populating Menu with Menu Items: #1 // Override this method of Activity class in order to create menu items. @Override public void onCreateContextMenu( ContextMenu menu, // Context menu that is being built View view, // The view for which the context menu is being built ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, view, menuInfo); menu.setHeaderTitle("Context menu"); menu.add(0, Menu.FIRST, Menu.NONE, "menu #1"); menu.add(0, Menu.FIRST + 1, Menu.NONE, "menu #2"); menu.add(0, Menu.FIRST + 2, Menu.NONE, "menu #3"); menu.add(0, Menu.FIRST + 3, Menu.NONE, "menu #4"); }
  • 9. How to handle Menu Selection? • When a menu item is selected from the Context Menu, onContextItemSelected() callback method of your Activity gets called > This callback passes you the MenuItem that has been selected. > You can identify the item by requesting the itemId, with getItemId(), which returns the integer that was assigned with the add() method. > Once you identify the menu item, you can take an appropriate action.
  • 10. Example: Handling Menu Selection /* Handles item selections */ public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_NEW_GAME: newGame(); return true; case MENU_QUIT: quit(); return true; } return false; }
  • 12. When to use Options Menu? • The Options Menu is where you should include basic application functions and any necessary navigation items (e.g., to a home screen or application settings).
  • 13. How Options Menu Work? • 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.
  • 14. Populating Menu with Menu Items: #1 /* Creates the menu items without Icons */ public boolean onCreateOptionsMenu(Menu menu) { // The add() method used in this sample takes four arguments: // groupId, itemId, order, and title. menu.add(0, MENU_NEW_GAME, 0, "New Game"); menu.add(0, MENU_QUIT, 0, "Quit"); return true; } /* Creates the menu items with Icons. Note that add() method returns newly created MenuItem object to set additional properties like an icon, a keyboard shortcut, an intent, and other settings for the item. */ public boolean onCreateOptionsMenu(Menu menu) { // The add() method used in this sample takes four arguments: // groupId, itemId, order, and title. menu.add(0, MENU_NEW_GAME, 0, "New Game").setIcon(R.drawable.menu_new_game_icon); menu.add(0, MENU_QUIT, 0, "Quit").setIcon(R.drawable.menu_quit_icon); return true; }
  • 15. How to handle Menu Selection? • When a menu item is selected from the Options Menu, onOptionsItemSelected() callback method of your Activity gets called > This callback passes you the MenuItem that has been selected. > You can identify the item by requesting the itemId, with getItemId(), which returns the integer that was assigned with the add() method. > Once you identify the menu item, you can take an appropriate action.
  • 16. Example: Handling Menu Selection /* Handles item selections */ public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_NEW_GAME: newGame(); return true; case MENU_QUIT: quit(); return true; } return false; }
  • 18. When to use SubMenu? • If you have several menu items that can be grouped together with a title, consider organizing them into a Submenu.
  • 19. Example: Creating Submenu public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); // Create submenu "File" SubMenu fileMenu = menu.addSubMenu("File"); fileMenu.add("New"); fileMenu.add("Open File"); fileMenu.add("Close"); fileMenu.add("Close All"); // Create submenu "Edit" SubMenu editMenu = menu.addSubMenu("Edit"); editMenu.add("Undo Typing"); editMenu.add("Redo"); editMenu.add("Cut"); return result; }
  • 21. Why using Menu Resource? • Instead of instantiating Menu objects in your application code, you should define a menu and all its items in an XML menu resource, then inflate the menu resource (load it as a programmable object) in your application code. • Defining your menus in XML is a better practice (than creating them in code) because it separates your interface design from your application code (the same as when you define your Activity layout in XML).
  • 22. When to Use Menu Resource File? • Create <menu_resource>.xml under res/menu/ directory • Inflate the Menu Resource file using inflate(<menu-resource-id>) method of the MenuInflator class > Menu objects are created from the Menu resource file
  • 23. Example: Inflating Menu Resource public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu XML resource. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.title_only, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.jump: Toast.makeText(this, "Jump up in the air!", Toast.LENGTH_LONG) .show(); return true; case R.id.dive: Toast.makeText(this, "Dive into the water!", Toast.LENGTH_LONG) .show(); return true; }
  • 24. Example: Menu Resource File <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/jump" android:title="Jump!" android:icon="@drawable/draw_jump" /> <item android:id="@+id/dive" android:title="Dive!" android:icon="@drawable/draw_dive" /> </menu>