SlideShare una empresa de Scribd logo
1 de 25
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Android animation
Android animationAndroid animation
Android animation
Krazy Koder
 
android layouts
android layoutsandroid layouts
android layouts
Deepa Rani
 
Android ui dialog
Android ui dialogAndroid ui dialog
Android ui dialog
Krazy Koder
 
Android ui layout
Android ui layoutAndroid ui layout
Android ui layout
Krazy Koder
 
Visual basic ppt for tutorials computer
Visual basic ppt for tutorials computerVisual basic ppt for tutorials computer
Visual basic ppt for tutorials computer
simran153
 
Android notification
Android notificationAndroid notification
Android notification
Krazy Koder
 

La actualidad más candente (20)

Java swing
Java swingJava swing
Java swing
 
Android activity lifecycle
Android activity lifecycleAndroid activity lifecycle
Android activity lifecycle
 
Android animation
Android animationAndroid animation
Android animation
 
android layouts
android layoutsandroid layouts
android layouts
 
Android Navigation Component
Android Navigation ComponentAndroid Navigation Component
Android Navigation Component
 
Fragment
Fragment Fragment
Fragment
 
Android intents
Android intentsAndroid intents
Android intents
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Android ui dialog
Android ui dialogAndroid ui dialog
Android ui dialog
 
Introduction to HTML5 Canvas
Introduction to HTML5 CanvasIntroduction to HTML5 Canvas
Introduction to HTML5 Canvas
 
Android ui layout
Android ui layoutAndroid ui layout
Android ui layout
 
Android User Interface
Android User InterfaceAndroid User Interface
Android User Interface
 
Android Fragment
Android FragmentAndroid Fragment
Android Fragment
 
AndroidManifest
AndroidManifestAndroidManifest
AndroidManifest
 
Awt, Swing, Layout managers
Awt, Swing, Layout managersAwt, Swing, Layout managers
Awt, Swing, Layout managers
 
Layouts in android
Layouts in androidLayouts in android
Layouts in android
 
Visual basic ppt for tutorials computer
Visual basic ppt for tutorials computerVisual basic ppt for tutorials computer
Visual basic ppt for tutorials computer
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Android notification
Android notificationAndroid notification
Android notification
 

Destacado

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 User Interface: Basic Form Widgets
Android User Interface: Basic Form WidgetsAndroid User Interface: Basic Form Widgets
Android User Interface: Basic Form Widgets
Ahsanul Karim
 

Destacado (19)

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
 
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
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android Fragments
 
Android User Interface: Basic Form Widgets
Android User Interface: Basic Form WidgetsAndroid User Interface: Basic Form Widgets
Android User Interface: Basic Form Widgets
 
Android Application Development
Android Application DevelopmentAndroid Application Development
Android Application Development
 

Similar a 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 4: Android: UI Widgets
Day 4: Android: UI WidgetsDay 4: Android: UI Widgets
Day 4: Android: UI Widgets
Ahsanul Karim
 
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
 

Similar a 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 4: Android: UI Widgets
Day 4: Android: UI WidgetsDay 4: Android: UI Widgets
Day 4: Android: UI Widgets
 
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
 

Más de 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
 

Último

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
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
 

Último (20)

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
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
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
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
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
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
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 

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>