You are on page 1of 45

Chapter 03(Part2)

Menus, Dialogues

Tagele B
1
Menu
Appear whenever the user presses the menu
button.
Useful for giving different options without leaving
the current Activity
Dont make too big menus, or theyll cover entirely
the Activity
3 types
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
Is afloating menuthat appears when the user

performs a long-click on an element.


It provides actions that affect the selected content or
2
Creating a Menu
Two methods (again):
XML
Place a file inside res/menu/

Inflate the menu inside the Activity

Useful if you want to create the same menu

inside different activities

Java
Create the menu directly inside the activity

3
Defining a Menu in XML
For all menu types, Android provides a
standard XML format to define menu items.
Define a menu and all its items in an
XMLmenu resource then inflate the menu
resource (load it as aMenuobject) in
activity.
Using a menu resource is a good practice
for a few reasons:
It's easier to visualize the menu structure in
XML.
It separates the content for the menu from
application's behavioral code.
It allows to create alternative menu
4
Contd.
To define the menu, create an XML file
inside project'sres/menu/directory and
build the menu with the following elements:
<menu>
Defines aMenu, which is a container for menu items.

A<menu>element must be the root node for the file

and can hold one or


more<item>and<group>elements.
<item>
Creates aMenuItem, which represents a single item in

a menu.

It may contain a nested<menu>element in order to
create a submenu.
<group>
An optional, invisible container for<item>elements.

It allows you to categorize menu items so they share


5
Menu - Example

6
The <item> element
The<item>element supports several
attributes you can use to define an item's
appearance and behavior.
The items element has the following
important attributes:
android:id
A resource ID that's unique to the item, which

allows the application can recognize the item


when the user selects it.
android:icon
A reference to a drawable to use as the

item's icon.android:title
A reference to a string to use as the item's

title. 7
Adding a Sub Menu
You can add a submenu to an item in any menu
(except a submenu) by adding a<menu>element
as the child of an<item>.
Submenus are useful when your application has a
lot of functions that can be organized
To use into
the menu topics,
in activity,
like items in a PC application's menu
inflate the bar
menu (File, Edit,
resource
View, etc.). usingMenuInflater.inflate().
For example:

8
Creating an Options Menu
The options menu is where you should include
actions and other options that are relevant
to the current activity context, such as
"Search," "Compose email," and "Settings.
To specify the options menu for an activity,
overrideonCreateOptionsMenu(). In this method,
you can inflate your menu resource (defined in
XML) into theMenuprovided in the callback.
For example:

You can also add menu items usingadd()and


retrieve items withfindItem()to revise their 9
Handling click events
When the user selects an item from the options
menu (including action items in the action bar),
the system calls your
activity'sonOptionsItemSelected()method, which
passes theMenuItemselected.
You can identify the item by callinggetItemId(),
which returns the unique ID for the menu item
(defined by the android:idattribute in the menu
resource or with an integer given to
theadd()method).
10
Contd. - Example

When you successfully handle a menu item, returntrue.


If you don't handle the menu item, you should call the
superclass implementation ofonOptionsItemSelected()(the
default implementation returns false).
11
Creating Contextual Menus
A contextual menu offers actions that affect a
specific item or context frame in the UI.
You can provide a context menu for any view, but
they are most often used for items in
aListView,GridView, or other view collections in
which the user can perform direct actions on each
item.

Screenshots of a floating context menu (left) and the contextual 12


Contd.
There are two ways to provide contextual
actions:
In afloating context menu. A menu appears as
a floating list of menu items (similar to a dialog)
when the user performs a long-click (press and
hold) on a view that declares support for a
context menu. Users can perform a contextual
action on one item at a time.
In thecontextual action mode. This mode is a
system implementation of ActionModethat
displays acontextual action barat the top of
the screen with action items that affect the
selected item(s). When this mode is active,
users can perform an action on multiple items
at once (if your app allows it). 13
Creating a floating context
menu
To provide a floating context menu:
Register theViewto which the context menu
should be associated by
callingregisterForContextMenu()and pass it
theView.If your activity uses
aListVieworGridViewand you want each item
to provide the same context menu, register all
items for a context menu by passing
theListVieworGridViewto
registerForContextMenu().
Implement theonCreateContextMenu()method
in yourActivity. When the registered view
receives a long-click event, the system calls
youronCreateContextMenu()method. This is
where you define the menu items, usually by 14
Example

MenuInflaterallows you to inflate the context


menu from amenu resource. The callback method
parameters include theViewthat the user selected
and aContextMenu. ContextMenuInfoobject that
provides additional information about the item
selected.
If your activity has several views that each provide
a different context menu, you might use these
parameters to determine which context menu to 15
Handling click events
ImplementonContextItemSelected( ):
When the user selects a menu item, the system calls this
method so you can perform the appropriate action.

16
Creating a Popup Menu
APopupMenuis a modal menu anchored to
aView. It appears below the anchor view if there is
room, or above the view otherwise. It's useful for:
Providing an overflow-style menu for actions thatrelate
tospecific content (such as Gmail's email headers).
Providing a second part of a command sentence (such as
a button marked "Add" that produces a popup menu with
different "Add" options).
Providing a drop-down similar toSpinnerthat does not
retain a persistent selection.
If youdefine your menu in XML, here's how you
can show the popup menu:
Instantiate aPopupMenuwith its constructor, which takes
the current applicationContextand theViewto which the
menu should be anchored.
UseMenuInflaterto inflate your menu resource into
theMenuobject returned byusing PopupMenu.inflate(). 17
Example

18
Handling click events
To perform an action when the user selects a menu
item, you must implement the
PopupMenu.OnMenuItemClickListenerinterface
and register it with yourPopupMenuby calling
setOnMenuItemclickListener().
When the user selects an item, the system calls
theonMenuItemClick() callback in your interface.

19
Contd.

20
Creating Menu Groups
A menu group is a collection of menu items
that share certain traits.
With a group, you can:
Show or hide all items withsetGroupVisible()
Enable or disable all items
withsetGroupEnabled()
Specify whether all items are checkable
withsetGroupCheckable()

You can create a group by


nesting<item>elements inside 21
Example

22
Using checkable menu items
A menu can be useful as an interface for turning
options on and off, using a checkbox for stand-
alone options, or radio buttons for groups of
mutually exclusive options.
You can define the checkable behavior for
individual menu items using the
android:checkableattribute in
the<item>element, or for an entire group with
theandroid:checkableBehaviorattribute in
the<group>element.

23
Contd.
Theandroid:checkableBehaviorattribute accepts
either:
Single
Only one item from the group can be checked (radio

buttons)
all
All items can be checked (checkboxes)

none

No items are checkable
You can apply a default checked state to an item
using theandroid:checkedattribute in
the<item>element and change it in code with
thesetChecked()method.
When a checkable item is selected, the system
calls your respective item-selected callback
method (such as onOptionsItemSelected()). 24
Example

25
Dialogs
A dialog is a small window that prompts the
user to make a decision or enter additional
information.
A dialog does not fill the screen and is
normally used for modal events that
require users to take an action before they
can proceed.

26
Contd.
TheDialogclass is the base class for dialogs, but
you have to use one of the following subclasses:
AlertDialog: A dialog that can show a title, up to three
buttons, a list of selectable items, or a custom layout.
DatePickerDialogorTimePickerDialog: A dialog with a pre-
defined UI that allows the user to select a date or time.
These classes define the style and structure for
your dialog, but you should use
aDialogFragmentas a container for your dialog.
The DialogFragmentclass provides all the controls
you need to create your dialog and manage its
appearance, instead of calling methods on
theDialogobject.
UsingDialogFragmentto manage the dialog
ensures that it correctly handles lifecycle events
such as when the user presses theBack button or 27
Creating a Dialog Fragment
You can accomplish a wide variety of dialog
designs by extending DialogFragmentand creating
aAlertDialogin theonCreateDialog() callback
method.

28
Building an Alert Dialog
TheAlertDialogclass allows you to build a variety
of dialog designs and is often the only dialog class
you'll need. As shown in figure, there are three
regions of an alert dialog:
Title: This is optional and should be used only when the
content area is occupied by a detailed message, a list, or
custom layout. If you need to state a simple message or
question, you don't need a title.
Content area: This can display a message, a list, or
other custom layout.
Action buttons: There should be no more than three
action buttons in a dialog.

29
Contd.

30
Adding buttons
To add action buttons, call thesetPositiveButton()
andsetNegativeButton()methods:

31
Contd.
Theset...Button()methods require a title for the
button (supplied by astring resource) and a
DialogInterface.OnClickListenerthat defines the
action to take when the user presses the button.
There are three different action buttons you can
add:
Positive: You should use this to accept and continue with
the action (the "OK" action).
Negative: You should use this to cancel the action.
Neutral: You should use this when the user may not want
to proceed with the action, but doesn't necessarily want
to cancel. It appears between the positive and negative
buttons. For example, the action might be "Remind me
later.
You can add only one of each button type to
anAlertDialog. That is, you cannot have more than 32
Adding a list
There are three kinds of lists available with the
AlertDialogAPIs:
A traditional single-choice list
A persistent single-choice list (radio buttons)
A persistent multiple-choice list (checkboxes)
To create a single-choice list like the one in figure,
use thesetItems()method:

33
Adding a persistent multiple-choice or
single-choice list
To add a list of multiple-choice items (checkboxes)
or single-choice items (radio buttons), use the
setMultiChoiceItems()orsetSingleChoiceItems()me
thods, respectively.
For example, here's how you can create a multiple-
choice list like the one shown in figure that saves
the selected items in anArrayList:

34
Contd.

35
Contd.

36
Creating a Custom Layout
If you want a custom layout in a dialog, create a
layout and add it to anAlertDialogby
callingsetView()on
yourAlertDialog.Builderobject.
By default, the custom layout fills the dialog
window, but you can still
useAlertDialog.Buildermethods to add buttons
and a title.
For example, here's the layout file for the dialog in
Figure:

37
Contd.

38
Contd.
To inflate the layout in yourDialogFragment, get
aLayoutInflaterwithgetLayoutInflater()and call
inflate(), where the first parameter is the layout
resource ID and the second parameter is a parent
view for the layout. You can then callsetView()to
place the layout in the dialog.

39
Passing Events Back to the
Dialog's Host
When the user touches one of the dialog's
action buttons or selects an item from its
list, yourDialogFragment might perform
the necessary action itself, but often you'll
want to deliver the event to the activity or
fragment that opened the dialog.
To do this, define an interface with a
method for each type of click event. Then
implement that interface in the host
component that will receive the action
events from the dialog.
For example, here's aDialogFragmentthat
defines an interface through which it 40
Contd.

41
Contd.
The activity hosting the dialog creates an instance
of the dialog with the dialog fragment's
constructor and receives the dialog's events
through an implementation of
theNoticeDialogListenerinterface:

42
Contd.
Because the host activity implements
theNoticeDialogListenerwhich is enforced by
theonAttach() callback method shown abovethe
dialog fragment can use the interface callback
methods to deliver click events to the activity:

43
Showing a Dialog
When you want to show your dialog, create an
instance of yourDialogFragmentand callshow(),
passing the FragmentManagerand a tag name for
the dialog fragment.
You can get theFragmentManagerby
callinggetSupportFragmentManager()from
theFragmentActivityor
getFragmentManager()from aFragment.
For example:

44
Dismissing a Dialog
When the user touches any of the action buttons
created with anAlertDialog.Builder, the system
dismisses the dialog for you.
The system also dismisses the dialog when the
user touches an item in a dialog list, except when
the list uses radio buttons or checkboxes.
Otherwise, you can manually dismiss your dialog
by callingdismiss()on your DialogFragment.
In case you need to perform certain actions when
the dialog goes away, you can implement
theonDismiss() method in yourDialogFragment.
You can alsocancela dialog. This is a special
event that indicates the user explicitly left the
dialog without completing the task. This occurs if
the user presses theBackbutton, touches the 45

You might also like