SlideShare ist ein Scribd-Unternehmen logo
1 von 10
Chapter 15
Menus in Android
By
Dr. Ramkumar Lakshminarayan
Introduction
Menus are a common user interface component in many types of applications. To
provide a familiar and consistent user experience, you should use the Menu APIs to present
user actions and other options in your activities.
Menus
Beginning with Android 3.0 (API level 11), Android-powered devices are no longer
required to provide a dedicated Menu button. With this change, Android apps should migrate
away from a dependence on the traditional 6-item menu panel and instead provide an action
bar to present common user actions.
Although the design and user experience for some menu items have changed, the
semantics to define a set of actions and options is still based on the Menu APIs. The three
fundamental types of menus or action presentations on all versions of Android are:
 Options menu and action bar
 Context menu and contextual action mode
 Popup menu
Options menu and action bar
The options menu is the primary collection of menu items for an activity. It's where
you should place actions that have a global impact on the app, such as "Search," "Compose
email," and "Settings."
Context menu and contextual action mode
A context menu is a floating menu that appears when the user performs a long-click
on an element. It provides actions that affect the selected content or context frame.
Popup menu
A popup menu displays a list of items in a vertical list that's anchored to the view that
invoked the menu. It's good for providing an overflow of actions that relate to specific
content or to provide options for a second part of a command. Actions in a popup menu
should not directly affect the corresponding content—that's what contextual actions are for.
Rather, the popup menu is for extended actions that relate to regions of content in your
activity.
Example Options Menu
Create a new application and name it as Optionmenu. In the activity_main.xml use the
default code:
In the resmenuactivity_main.xml add a menu item about as follows:
In Androidmanifest.xml add the following lines of code <uses-sdk> to allow the user
to access the internet.
In MainActivity.java OnOptionsItemSelected() is used to handle the menu selected.
URI class can both parse URI strings into parts and compose URI strings from parts.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/menu_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/menu_settings"/>
<item android:id="@+id/about"
android:orderInCategory="101"
android:title="About" />
</menu>
<uses-permission android:name="android.permission.INTERNET"/>
Figure 15.1 Menu in Screen
package com.mjs.optionmenu;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
Intent intent =null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.rajaramsystems.com"));
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
When the About in the menu is clicked, the screen will navigate to a website. The
following screenshot shows the action when the About menu is clicked
Figure 15.2 About Menu Clicked
Example – Context Menu
In resmenumain_activity.xml add the following code to add the list of items.
In reslayoutactivity_main.xml add a button control with the following codes:
<menu
xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/menu_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/menu_settings"/>
<item
android:id="@+id/menu_delete"
android:title="Delete Item"/>
<item
android:id="@+id/menu_copy"
android:title="Copy Item"/>
<item
android:id="@+id/menu_edit"
android:title="Edit Item"/>
</menu>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_alignParentTop="true"
android:layout_marginLeft="24dp"
android:text="Click Me !" />
Then make use of onCreateContextMenu() as well as onContextItemSelected() within
the Activity in order to inflate the menu and also handle user selection.
Using Custom Menu in Activity
In onCreate() add the button and assign the Event Listener with the following code:
When the code is executed and click the Click Me Button, Context Menu will be shown as
follows:
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.activity_main, menu);
menu.setHeaderTitle("Select an Option");
}
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_delete:
Toast.makeText(MainActivity.this,"Delete Operation is
performed!",Toast.LENGTH_SHORT ).show();
return true;
case R.id.menu_copy:
Toast.makeText(MainActivity.this,"Copy Operation is
performed!",Toast.LENGTH_SHORT ).show();
return true;
case R.id.menu_edit:
Toast.makeText(MainActivity.this,"Edit Operation is
performed!",Toast.LENGTH_SHORT ).show();
return true;
}
return super.onContextItemSelected(item);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button1);
registerForContextMenu(btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openContextMenu(v);
}
});
}
Figure 15.3 Context Menu
Complete Code of MainActivity.java
package com.mjs.contextmenu;
import android.os.Bundle;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button1);
registerForContextMenu(btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openContextMenu(v);
}
});
}
@Override
public void onCreateContextMenu(ContextMenu menu, View
v,ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.activity_main, menu);
menu.setHeaderTitle("Select an Option");
}
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_delete:
Toast.makeText(MainActivity.this,"Delete Operation is
performed!",Toast.LENGTH_SHORT ).show();
return true;
case R.id.menu_copy:
Toast.makeText(MainActivity.this,"Copy Operation is
performed!",Toast.LENGTH_SHORT ).show();
return true;
case R.id.menu_edit:
Toast.makeText(MainActivity.this,"Edit Operation is
performed!",Toast.LENGTH_SHORT ).show();
return true;
}
return super.onContextItemSelected(item);
}
}
Popup Menu
Popup menus in android are useful for displaying extended options associated with a
specific action. For eg: ‘send’ action could have multiple extended options, like ‘send by
email’ or ‘send by sms’ etc. Unlike android context menus they can be invoked by any event
such a button click not just long clicks. They are associated with the specific view that
invoked it and each view in an activity can have its own popup window.
Creating the Popup Menu
Create a new instance of PopupMenu class and pass the instance of the Context (
usually the current activity) and the view (for which the pop-up menu is desired) as
arguments.
Inflate the menu resource using:
 popupMenu.inflate () if you are using Android 4.0 SDK and above (or)
 MenuInflater class (popupMenu.getMenuInflater().inflate() method) if you are using
Android 3.0 SDK
 Call popupMenu.show() to display the menu
Override the popupMenu.setOnMenuItemClickListener () method and provide a call back
for handling user selections. The use selected menu item is passed in as argument to the
callback method.
Create a new project with the name Popupmenu and use the following code for
reslayoutactivity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
<Button android:id="@+id/popupMenuBtn"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Show me the Popup"
android:layout_gravity="center"
android:gravity="center"/>
</RelativeLayout>
In resmenuactivity_main.xml, add the following lines of code:
In resvaluescolor.xml create the values for colors using the following code:
In resvaluesstrings.xml change the value for hello world as “Example for popup
Menu” and change the code as follows:
In MainActivity.java ensure that the following packages are used and use the code as
follows:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/menu_red" android:title="Red" />
<item android:id="@+id/menu_green" android:title="Green"/>
<item android:id="@+id/menu_blue" android:title="Blue"/>
</menu>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red">#ff0000</color>
<color name="green">#00ff00</color>
<color name="blue">#0000ff</color>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Popmenu</string>
<string name="hello_world">Example for Popup Menu</string>
</resources>
import android.os.Bundle;
import android.app.Activity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
Code of MainActivity.java for popup menu
public class MainActivity extends Activity {
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* A Button that acts as the view element for the popup menu.
*/
final Button btn = (Button) findViewById(R.id.popupMenuBtn);
/**
* Step 1: Create a new instance of popup menu
*/
final PopupMenu popupMenu = new PopupMenu(this, btn);
/**
* Step 2: Inflate the menu resource. Here the menu resource is
* defined in the res/menu project folder
*/
popupMenu.inflate(R.menu.activity_main);
/**
* Step 3: Call show() method on the popup menu to display the
* menu when the button is clicked.
*/
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupMenu.show();
}
});
/**
* Handle menu item clicks
*/
popupMenu.setOnMenuItemClickListener(
new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_red:
btn.setBackgroundResource(R.color.red);
break;
case R.id.menu_blue:
btn.setBackgroundResource(R.color.blue);
break;
case R.id.menu_green:
btn.setBackgroundResource(R.color.green);
break;
}
return true;
}
});
}
}
Figure 15.4 Popup Menu.
When the Red Option is clicked the button color will be changed to Red and it is
applicable for Green and Blue Button also.
Summary
In this unit we have seen Menus are a common user interface component in many
types of applications. We have seen the examples of creating application with Options Menu,
Context and Popup Menu.

Weitere ähnliche Inhalte

Was ist angesagt?

Android notification
Android notificationAndroid notification
Android notification
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
 
Android notifications
Android notificationsAndroid notifications
Android notifications
Ketan Raval
 
Android App Development 03 : Widget &amp; UI
Android App Development 03 : Widget &amp; UIAndroid App Development 03 : Widget &amp; UI
Android App Development 03 : Widget &amp; UI
Anuchit Chalothorn
 
Day 4: Android: UI Widgets
Day 4: Android: UI WidgetsDay 4: Android: UI Widgets
Day 4: Android: UI Widgets
Ahsanul Karim
 

Was ist angesagt? (20)

Menu stripe
Menu stripeMenu stripe
Menu stripe
 
Androd Listeners
Androd ListenersAndrod Listeners
Androd Listeners
 
Android user interface design-chapter13
Android user interface design-chapter13Android user interface design-chapter13
Android user interface design-chapter13
 
Android notification
Android notificationAndroid notification
Android notification
 
Android User Interface: Basic Form Widgets
Android User Interface: Basic Form WidgetsAndroid User Interface: Basic Form Widgets
Android User Interface: Basic Form Widgets
 
Android App Development - 02 Activity and intent
Android App Development - 02 Activity and intentAndroid App Development - 02 Activity and intent
Android App Development - 02 Activity and intent
 
Creating avatars 1
Creating avatars 1Creating avatars 1
Creating avatars 1
 
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
 
Lesson 9
Lesson 9Lesson 9
Lesson 9
 
360 Flex Atlanta
360 Flex Atlanta360 Flex Atlanta
360 Flex Atlanta
 
Android Lesson 2
Android Lesson 2Android Lesson 2
Android Lesson 2
 
Visual Basic menu
Visual Basic menuVisual Basic menu
Visual Basic menu
 
Android Training (Notifications)
Android Training (Notifications)Android Training (Notifications)
Android Training (Notifications)
 
Android App Dev Manual-1.doc
Android App Dev Manual-1.docAndroid App Dev Manual-1.doc
Android App Dev Manual-1.doc
 
Android development session 2 - intent and activity
Android development   session 2 - intent and activityAndroid development   session 2 - intent and activity
Android development session 2 - intent and activity
 
Android notifications
Android notificationsAndroid notifications
Android notifications
 
Android App Development 03 : Widget &amp; UI
Android App Development 03 : Widget &amp; UIAndroid App Development 03 : Widget &amp; UI
Android App Development 03 : Widget &amp; UI
 
Day 4: Android: UI Widgets
Day 4: Android: UI WidgetsDay 4: Android: UI Widgets
Day 4: Android: UI Widgets
 
Toolbar
ToolbarToolbar
Toolbar
 
Android session 3
Android session 3Android session 3
Android session 3
 

Andere mochten auch

Component interface
Component interfaceComponent interface
Component interface
JAYAARC
 

Andere mochten auch (20)

Introduction to Android (in tamil)
Introduction to Android (in tamil)Introduction to Android (in tamil)
Introduction to Android (in tamil)
 
Android views and layouts-chapter4
Android views and layouts-chapter4Android views and layouts-chapter4
Android views and layouts-chapter4
 
Cloud performance tools
Cloud performance toolsCloud performance tools
Cloud performance tools
 
Android building blocks and application life cycle-chapter3
Android building blocks and application life cycle-chapter3Android building blocks and application life cycle-chapter3
Android building blocks and application life cycle-chapter3
 
Android practice of layout in application-chapter6
Android practice of layout in application-chapter6Android practice of layout in application-chapter6
Android practice of layout in application-chapter6
 
Android style resource and other resources types-chapter12
Android style resource and other resources types-chapter12Android style resource and other resources types-chapter12
Android style resource and other resources types-chapter12
 
Android Tips (Tamil)
Android Tips (Tamil)Android Tips (Tamil)
Android Tips (Tamil)
 
Android Application using seekbar (in tamil)
Android Application using seekbar (in tamil)Android Application using seekbar (in tamil)
Android Application using seekbar (in tamil)
 
Creating Image Gallery - Android app (in tamil)
Creating Image Gallery - Android app (in tamil)Creating Image Gallery - Android app (in tamil)
Creating Image Gallery - Android app (in tamil)
 
Concurrency control
Concurrency controlConcurrency control
Concurrency control
 
Rating Bar in Android Example
Rating Bar in Android ExampleRating Bar in Android Example
Rating Bar in Android Example
 
Component interface
Component interfaceComponent interface
Component interface
 
A Study of Computer Applications in the Management of Aavin Dairy Cooperative...
A Study of Computer Applications in the Management of Aavin Dairy Cooperative...A Study of Computer Applications in the Management of Aavin Dairy Cooperative...
A Study of Computer Applications in the Management of Aavin Dairy Cooperative...
 
FORWARD CHAINING AND BACKWARD CHAINING SYSTEMS IN ARTIFICIAL INTELIGENCE
FORWARD CHAINING AND BACKWARD CHAINING SYSTEMS IN ARTIFICIAL INTELIGENCEFORWARD CHAINING AND BACKWARD CHAINING SYSTEMS IN ARTIFICIAL INTELIGENCE
FORWARD CHAINING AND BACKWARD CHAINING SYSTEMS IN ARTIFICIAL INTELIGENCE
 
Topic 8 expert system
Topic 8 expert systemTopic 8 expert system
Topic 8 expert system
 
Android development - the basics, MFF UK, 2014
Android development - the basics, MFF UK, 2014Android development - the basics, MFF UK, 2014
Android development - the basics, MFF UK, 2014
 
Android Development: The Basics
Android Development: The BasicsAndroid Development: The Basics
Android Development: The Basics
 
2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShare
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShare
 

Ähnlich wie Android menus in android-chapter15

android activity
android activityandroid activity
android activity
Deepa Rani
 
How to create android push notifications with custom view
How to create android push notifications with custom viewHow to create android push notifications with custom view
How to create android push notifications with custom view
PushApps - Content Recommendation in Push Notifications
 

Ähnlich wie Android menus in android-chapter15 (20)

Learn Xamarin Absolute Beginners - Permissions, Building the App GUI & Menus
Learn Xamarin Absolute Beginners - Permissions, Building the App GUI & MenusLearn Xamarin Absolute Beginners - Permissions, Building the App GUI & Menus
Learn Xamarin Absolute Beginners - Permissions, Building the App GUI & Menus
 
Chapter 2 lesson-1 adding the action bar
Chapter 2 lesson-1 adding the action barChapter 2 lesson-1 adding the action bar
Chapter 2 lesson-1 adding the action bar
 
01 10 - graphical user interface - others
01  10 - graphical user interface - others01  10 - graphical user interface - others
01 10 - graphical user interface - others
 
Android apps development
Android apps developmentAndroid apps development
Android apps development
 
"Android" mobilių programėlių kūrimo įvadas #2
"Android" mobilių programėlių kūrimo įvadas #2"Android" mobilių programėlių kūrimo įvadas #2
"Android" mobilių programėlių kūrimo įvadas #2
 
A comprehensive guide on developing responsive and common react filter component
A comprehensive guide on developing responsive and common react filter componentA comprehensive guide on developing responsive and common react filter component
A comprehensive guide on developing responsive and common react filter component
 
Android UI Fundamentals part 1
Android UI Fundamentals part 1Android UI Fundamentals part 1
Android UI Fundamentals part 1
 
Using android's action bar
Using android's action barUsing android's action bar
Using android's action bar
 
Create New Android Layout
Create New Android LayoutCreate New Android Layout
Create New Android Layout
 
android activity
android activityandroid activity
android activity
 
Android App Development (Basics)
Android App Development (Basics)Android App Development (Basics)
Android App Development (Basics)
 
Android Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_androidAndroid Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_android
 
Android Button
Android ButtonAndroid Button
Android Button
 
How to create android push notifications with custom view
How to create android push notifications with custom viewHow to create android push notifications with custom view
How to create android push notifications with custom view
 
Leture5 exercise onactivities
Leture5 exercise onactivitiesLeture5 exercise onactivities
Leture5 exercise onactivities
 
Lecture exercise on activities
Lecture exercise on activitiesLecture exercise on activities
Lecture exercise on activities
 
Create an other activity lesson 3
Create an other activity lesson 3Create an other activity lesson 3
Create an other activity lesson 3
 
MenusAnddailogsinandroidddfdadusjsjdjdjs
MenusAnddailogsinandroidddfdadusjsjdjdjsMenusAnddailogsinandroidddfdadusjsjdjdjs
MenusAnddailogsinandroidddfdadusjsjdjdjs
 
Android
AndroidAndroid
Android
 
Create New Android Activity
Create New Android ActivityCreate New Android Activity
Create New Android Activity
 

Mehr von Dr. Ramkumar Lakshminarayanan

Mehr von Dr. Ramkumar Lakshminarayanan (20)

IT security awareness
IT security awarenessIT security awareness
IT security awareness
 
Basics of IT security
Basics of IT securityBasics of IT security
Basics of IT security
 
IT Security Awareness Posters
IT Security Awareness PostersIT Security Awareness Posters
IT Security Awareness Posters
 
Normalisation revision
Normalisation revisionNormalisation revision
Normalisation revision
 
Windows mobile programming
Windows mobile programmingWindows mobile programming
Windows mobile programming
 
Web technology today
Web technology todayWeb technology today
Web technology today
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Phonegap for Android
Phonegap for AndroidPhonegap for Android
Phonegap for Android
 
Create and Sell Android App (in tamil)
Create and Sell Android App (in tamil)Create and Sell Android App (in tamil)
Create and Sell Android App (in tamil)
 
Android app - Creating Live Wallpaper (tamil)
Android app - Creating Live Wallpaper (tamil)Android app - Creating Live Wallpaper (tamil)
Android app - Creating Live Wallpaper (tamil)
 
Android Animation (in tamil)
Android Animation (in tamil)Android Animation (in tamil)
Android Animation (in tamil)
 
Creating List in Android App (in tamil)
Creating List in Android App (in tamil)Creating List in Android App (in tamil)
Creating List in Android App (in tamil)
 
Single Touch event view in Android (in tamil)
Single Touch event view in Android (in tamil)Single Touch event view in Android (in tamil)
Single Touch event view in Android (in tamil)
 
Create Android App using web view (in tamil)
Create Android App using web view (in tamil)Create Android App using web view (in tamil)
Create Android App using web view (in tamil)
 
Hardware Interface in Android (in tamil)
Hardware Interface in Android (in tamil)Hardware Interface in Android (in tamil)
Hardware Interface in Android (in tamil)
 
GPS in Android (in tamil)
GPS in Android (in tamil)GPS in Android (in tamil)
GPS in Android (in tamil)
 
Using many languages in single Android App (in tamil)
Using many languages in single Android App (in tamil)Using many languages in single Android App (in tamil)
Using many languages in single Android App (in tamil)
 
SQLite in Android App (in tamil)
SQLite in Android App (in tamil)SQLite in Android App (in tamil)
SQLite in Android App (in tamil)
 
Shared Preference in Android App
Shared Preference in Android AppShared Preference in Android App
Shared Preference in Android App
 
Data Storage in Android App
Data Storage in Android AppData Storage in Android App
Data Storage in Android App
 

Kürzlich hochgeladen

Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Cara Menggugurkan Kandungan 087776558899
 

Kürzlich hochgeladen (6)

Mobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsMobile Application Development-Components and Layouts
Mobile Application Development-Components and Layouts
 
Android Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesAndroid Application Components with Implementation & Examples
Android Application Components with Implementation & Examples
 
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
 
Mobile App Penetration Testing Bsides312
Mobile App Penetration Testing Bsides312Mobile App Penetration Testing Bsides312
Mobile App Penetration Testing Bsides312
 
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
 
Mobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsMobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s Tools
 

Android menus in android-chapter15

  • 1. Chapter 15 Menus in Android By Dr. Ramkumar Lakshminarayan Introduction Menus are a common user interface component in many types of applications. To provide a familiar and consistent user experience, you should use the Menu APIs to present user actions and other options in your activities. Menus Beginning with Android 3.0 (API level 11), Android-powered devices are no longer required to provide a dedicated Menu button. With this change, Android apps should migrate away from a dependence on the traditional 6-item menu panel and instead provide an action bar to present common user actions. Although the design and user experience for some menu items have changed, the semantics to define a set of actions and options is still based on the Menu APIs. The three fundamental types of menus or action presentations on all versions of Android are:  Options menu and action bar  Context menu and contextual action mode  Popup menu Options menu and action bar The options menu is the primary collection of menu items for an activity. It's where you should place actions that have a global impact on the app, such as "Search," "Compose email," and "Settings." Context menu and contextual action mode A context menu is a floating menu that appears when the user performs a long-click on an element. It provides actions that affect the selected content or context frame. Popup menu A popup menu displays a list of items in a vertical list that's anchored to the view that invoked the menu. It's good for providing an overflow of actions that relate to specific content or to provide options for a second part of a command. Actions in a popup menu should not directly affect the corresponding content—that's what contextual actions are for. Rather, the popup menu is for extended actions that relate to regions of content in your activity.
  • 2. Example Options Menu Create a new application and name it as Optionmenu. In the activity_main.xml use the default code: In the resmenuactivity_main.xml add a menu item about as follows: In Androidmanifest.xml add the following lines of code <uses-sdk> to allow the user to access the internet. In MainActivity.java OnOptionsItemSelected() is used to handle the menu selected. URI class can both parse URI strings into parts and compose URI strings from parts. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/hello_world" /> </RelativeLayout> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/menu_settings" android:orderInCategory="100" android:showAsAction="never" android:title="@string/menu_settings"/> <item android:id="@+id/about" android:orderInCategory="101" android:title="About" /> </menu> <uses-permission android:name="android.permission.INTERNET"/>
  • 3. Figure 15.1 Menu in Screen package com.mjs.optionmenu; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends Activity { Intent intent =null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.about: intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.rajaramsystems.com")); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } }
  • 4. When the About in the menu is clicked, the screen will navigate to a website. The following screenshot shows the action when the About menu is clicked Figure 15.2 About Menu Clicked Example – Context Menu In resmenumain_activity.xml add the following code to add the list of items. In reslayoutactivity_main.xml add a button control with the following codes: <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/menu_settings" android:orderInCategory="100" android:showAsAction="never" android:title="@string/menu_settings"/> <item android:id="@+id/menu_delete" android:title="Delete Item"/> <item android:id="@+id/menu_copy" android:title="Copy Item"/> <item android:id="@+id/menu_edit" android:title="Edit Item"/> </menu> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1" android:layout_alignParentTop="true" android:layout_marginLeft="24dp" android:text="Click Me !" />
  • 5. Then make use of onCreateContextMenu() as well as onContextItemSelected() within the Activity in order to inflate the menu and also handle user selection. Using Custom Menu in Activity In onCreate() add the button and assign the Event Listener with the following code: When the code is executed and click the Click Me Button, Context Menu will be shown as follows: public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); getMenuInflater().inflate(R.menu.activity_main, menu); menu.setHeaderTitle("Select an Option"); } public boolean onContextItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.menu_delete: Toast.makeText(MainActivity.this,"Delete Operation is performed!",Toast.LENGTH_SHORT ).show(); return true; case R.id.menu_copy: Toast.makeText(MainActivity.this,"Copy Operation is performed!",Toast.LENGTH_SHORT ).show(); return true; case R.id.menu_edit: Toast.makeText(MainActivity.this,"Edit Operation is performed!",Toast.LENGTH_SHORT ).show(); return true; } return super.onContextItemSelected(item); } protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn=(Button)findViewById(R.id.button1); registerForContextMenu(btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openContextMenu(v); } }); }
  • 6. Figure 15.3 Context Menu Complete Code of MainActivity.java package com.mjs.contextmenu; import android.os.Bundle; import android.app.Activity; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn=(Button)findViewById(R.id.button1); registerForContextMenu(btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openContextMenu(v); } }); } @Override public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); getMenuInflater().inflate(R.menu.activity_main, menu); menu.setHeaderTitle("Select an Option"); } public boolean onContextItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.menu_delete: Toast.makeText(MainActivity.this,"Delete Operation is performed!",Toast.LENGTH_SHORT ).show(); return true; case R.id.menu_copy: Toast.makeText(MainActivity.this,"Copy Operation is performed!",Toast.LENGTH_SHORT ).show(); return true; case R.id.menu_edit: Toast.makeText(MainActivity.this,"Edit Operation is performed!",Toast.LENGTH_SHORT ).show(); return true; } return super.onContextItemSelected(item); } }
  • 7. Popup Menu Popup menus in android are useful for displaying extended options associated with a specific action. For eg: ‘send’ action could have multiple extended options, like ‘send by email’ or ‘send by sms’ etc. Unlike android context menus they can be invoked by any event such a button click not just long clicks. They are associated with the specific view that invoked it and each view in an activity can have its own popup window. Creating the Popup Menu Create a new instance of PopupMenu class and pass the instance of the Context ( usually the current activity) and the view (for which the pop-up menu is desired) as arguments. Inflate the menu resource using:  popupMenu.inflate () if you are using Android 4.0 SDK and above (or)  MenuInflater class (popupMenu.getMenuInflater().inflate() method) if you are using Android 3.0 SDK  Call popupMenu.show() to display the menu Override the popupMenu.setOnMenuItemClickListener () method and provide a call back for handling user selections. The use selected menu item is passed in as argument to the callback method. Create a new project with the name Popupmenu and use the following code for reslayoutactivity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/hello_world" /> <Button android:id="@+id/popupMenuBtn" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Show me the Popup" android:layout_gravity="center" android:gravity="center"/> </RelativeLayout>
  • 8. In resmenuactivity_main.xml, add the following lines of code: In resvaluescolor.xml create the values for colors using the following code: In resvaluesstrings.xml change the value for hello world as “Example for popup Menu” and change the code as follows: In MainActivity.java ensure that the following packages are used and use the code as follows: <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/menu_red" android:title="Red" /> <item android:id="@+id/menu_green" android:title="Green"/> <item android:id="@+id/menu_blue" android:title="Blue"/> </menu> <?xml version="1.0" encoding="utf-8"?> <resources> <color name="red">#ff0000</color> <color name="green">#00ff00</color> <color name="blue">#0000ff</color> </resources> <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Popmenu</string> <string name="hello_world">Example for Popup Menu</string> </resources> import android.os.Bundle; import android.app.Activity; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.PopupMenu;
  • 9. Code of MainActivity.java for popup menu public class MainActivity extends Activity { Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /** * A Button that acts as the view element for the popup menu. */ final Button btn = (Button) findViewById(R.id.popupMenuBtn); /** * Step 1: Create a new instance of popup menu */ final PopupMenu popupMenu = new PopupMenu(this, btn); /** * Step 2: Inflate the menu resource. Here the menu resource is * defined in the res/menu project folder */ popupMenu.inflate(R.menu.activity_main); /** * Step 3: Call show() method on the popup menu to display the * menu when the button is clicked. */ btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupMenu.show(); } }); /** * Handle menu item clicks */ popupMenu.setOnMenuItemClickListener( new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.menu_red: btn.setBackgroundResource(R.color.red); break; case R.id.menu_blue: btn.setBackgroundResource(R.color.blue); break; case R.id.menu_green: btn.setBackgroundResource(R.color.green); break; } return true; } }); } }
  • 10. Figure 15.4 Popup Menu. When the Red Option is clicked the button color will be changed to Red and it is applicable for Green and Blue Button also. Summary In this unit we have seen Menus are a common user interface component in many types of applications. We have seen the examples of creating application with Options Menu, Context and Popup Menu.