0% found this document useful (0 votes)
18 views97 pages

CH Two

This document provides an overview of the basics of Android User Interface, focusing on XML, Views, and Android Layouts. It explains XML structure, advantages, and validation methods, as well as the differences between XML and HTML. Additionally, it covers user interface controls, event listeners, and various layout types in Android development.

Uploaded by

matebearagaw6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views97 pages

CH Two

This document provides an overview of the basics of Android User Interface, focusing on XML, Views, and Android Layouts. It explains XML structure, advantages, and validation methods, as well as the differences between XML and HTML. Additionally, it covers user interface controls, event listeners, and various layout types in Android development.

Uploaded by

matebearagaw6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

Chapter - Two

Basics of Android User Interface


Part-I

Mobile Application Development


Contents
 In this Section, you will learn about:

XML Basics

Views (User Interface Controls)

Android Layouts
XML Basics
 It stands for eXtensible Markup Language (ML).

 Markup languages (MLs) are language that uses “markup” in order to

encode metadata in a text format, e.g. SGML, HTML, XHTML …. MLs but
XML is different.
 Unlike other MLs which have predefined tags, XML let you use your own tag.

 HTML allows you to create a web page using predefined tags like

<body>,<form>,<p>,<h1>, etc.

 But XML allows you to create a document you like say StudentProfile that has

your own tags like; studentname, age, sex etc.


Advantages of XML
 Self descriptive data - is data that describes both its content and
structure
 Designed to store and transport data not to display it
 Can be easily transported with no need for compatibility b/n
source & destination
 Created to provide an easy to use and store self describing data
 Not a replacement for HTML, often a complement to HTML
 Tags are not predefined.You must define your own tags
 Platform (hardware) and language (software) independent
XML Document Vs HTML Document
 HTML is a ML to create a structured document called HTML document
(Web Page)

 Similarly a document produced using XML is called XML document

 Likewise, HTML document has .html extension, XML document has


.xml

 Unlike HTML documents, which can only be viewed using HTML


browsers, XML documents or its part can be processed, displayed,
combined to form another, used as input for applications etc.
XML Document Structure
 The major portions of an XML document include the following:

The XML declaration

The Document Type Declaration

The Element data

The Attribute data


The Character data or XML content

 XML documents are allowed to include all or part of the above


components
Cont’d

1) Start by defining the XML declaration, called the XML prolog


<?xml version=“” encoding=“UTF-8”?>

2) Declaring the document type definition (DTD) -xml doc model against which the current
document you are creating to be “well formed” or “validated” you will declare the
DTD/Schema file in here.
Cont’d
 adding comments
 <!-- put your comment here -->
Rules of XML Structure
 All XML Elements Must Have a Closing Tag

 XML Tags Are Case Sensitive

 All XML Elements Must Have Proper Nesting

 All XML Documents Must Contain a Single Root Element

 Attribute Values Must Be Quoted

 Attributes May Only Appear Once in the Same Start Tag

 Attribute Values Cannot Contain References to External Entities


Cont’D
XML Validation
 XML file can be validated by using two ways:

I) Against DTD (Document Type Definition) and


II) Against XSD (XML Schema Definition) are used to define XML
structure
DTD and XML Schema
 DTD stands for Document Type Definition

 DTD defines the structure and the legal elements and attributes of an XML

document

 A "Valid" XML document is "Well Formed", as well as it conforms to the rules of

a DTD

 XML Schema describes the structure of an XML document, just like a DTD

 An XML document with correct syntax is called "Well Formed“

 An XML document validated against an XML Schema is both "Well Formed" and

"Valid"
Cont’D
Cont’D
Cont’D
 Description of XML Schema

 <xs:element name="employee"> : It defines the element name employee.

 <xs:complexType> : It defines that the element 'employee' is complex type.

 <xs:sequence> : It defines that the complex type is a sequence of elements.

 <xs:element name="firstname" type="xs:string"/> : It defines that the element

'firstname' is of string/text type.


 <xs:element name="lastname" type="xs:string"/> : It defines that the element

'lastname' is of string/text type.


 <xs:element name="email" type="xs:string"/> : It defines that the element

'email' is of string/text type.


Cont’d
 XML Schema Data types :there are two types of data types in XML schema.

Simple Type
The simpleType allows you to have text-based elements. It contains
less attributes, child elements, and cannot be left empty.
Complex Type
The complexType allows you to hold multiple attributes and
elements. It can contain additional sub elements and can be left
empty.
DTD vs XSD
XML document
XML allows creating document model in two types of modeling

1) Freeform XML Modelling: in this type there are minimal rules in the model &
you have the right to use any name for tags and tags can appear in any order.
Document created as such is called well-formed (legal XML syntax and
structure according to the XML specification) XML Document.

2) Strict XML Modeling:

If all documents to be created (known as document instances) has to follow all the
rules, tag precedence and tag naming when validated against the one specified in the
document model, the created instance is called Valid XML (one that is well-
formed and conforms to a structure outlined in a DTD or schema)
document.
Instance
<?xml version ="1.0" ?>
<Person_Details>
<person Nationality="Ethiopian">
<Name>Bekretsyon B.</Name>
<Address>Admas University
[email protected]</Address>
<State>AA</State>
<City>Adis abeba, Ethiopia</City>
<Zip> 0000000001000</Zip>
<Marital_status>Merried</Marital_status>
<PersonId>adm0123</PersonId>
</person>
<person>
<!- - I can add another person detail here -->
</person>
</Person_Details>
Views (User Interface Controls)
 An Android application UI is everything that the user can see and interact

with.

 A View is an object that draws something on the screen that the user can

interact with and

 ViewGroup is an object that holds other View (and ViewGroup) objects in

order to define the layout of the user interface.

 All user interface elements in an Android app are built


using View and ViewGroup objects.
Cont’D
 Android provides a collection of both View and ViewGroup subclasses that
offer common input controls (such as buttons and text fields) and various
layout models (such as a linear or relative layout).
Methods to Create a User Interface
 There are two ways to create a user interface (UI) in Android:
 Declaratively and programmatically.

 They are quite different but often are used together to get the job done.

1) Declarative User Interface

 The declarative approach involves using XML to declare what the UI


will look like,
 Similar to creating a web page using HTML. You write tags and specify
elements to appear on your screen.
 If you have ever hand coded an HTML page, you did pretty much the
same work as creating an Android screen.
Cont’D
Cont’D
 Advantage:

 XML is fairly human-readable, and even people who are unfamiliar with the
Android platform and framework can readily determine the intent of the user
interface.
 The disadvantage

 It doesn’t provide a good way of handling user input. That’s where the
programmatic approach comes in.
2) Programmatic User Interface
 A programmatic user interface involves writing Java code to develop the UI.

 If you have ever done any Java AWT(Abstract Window Toolkit) or Java Swing
development, Android is pretty much the same in that respect. It is similar to
many UI toolkits in other languages as well.
Cont’D
 Basically, if you want to create a button programmatically,
 Declare the button variable
 Create an instance of it
 Add it to a container and
 Set any button properties that may make sense, such as color, text, text size,
background, and so on.
 Everything you can do on declaratively, you can also do
programmatically.
 But Java also allows you to specify what happens when that button is
actually clicked. This is the main advantage of a programmatic approach
to the user interface.
 So which approach to use?
 The best practice is to use both, you’d use XML to declare what the
“button” looks like and Java to specify what it does.
Cont’D
Views are building blocks of Activities/UI
Create using Programmatic UI layout
Common Controls
Cont’d
 Input controls are the interactive components in your app's user interface.

 Android provides a wide variety of controls you can use in your UI, such as

buttons, text fields, seek bars, check boxes, zoom buttons,


toggle buttons, and many more.
Event Listener (Input Events)
 An interface, in the View class, that contains a single callback method

 Called by the Android framework when theView is triggered

 Multiple Event Listeners (Interfaces):

 View.OnClickListener - onClick()

 View.OnLongClickListener - onLongClick()

 View.OnFocusChangeListener - onFocusChange()

 View.OnKeyListener - onKey()

 View.OnTouchListener - onTouch()

 View.OnCreateContextMenuListener -onCreateContextMenu()
Cont’D
 Example: onClick() for Button view
Android layouts
 Android organizes its UI elements into views and layouts.

 Everything you see, such as a button, label, or text box, is a view.

 Layouts organize views, such as grouping together a button and label or a

group of these elements.

 If you have prior experience with Java Swing, layouts are similar to Java

containers and views are similar to Java components.

 Views in Android are sometimes referred to as widgets.

 A layout can contain other children. Those children can furthermore be

layouts themselves, allowing for a complex user interface structure.


Cont’D
 A layout is responsible for allocating space for each child.

 A layout defines the visual structure for a user interface, such as the UI for
an activity or app widget.
 Can be specified in

 res/layout/activity_main.xml

 Each Activity can have it's own layout

32
Cont’d

33
Common Layouts
 Linear Layout: is a view group that aligns all children in a single direction,
vertically or horizontally.
 Relative Layout: is a view group that displays child views in relative positions.

 Enables you to specify the location of child objects relative to each other (child
A to the left of child B) or to the parent (aligned to the top of the parent).
 Table Layout: is a view that groups views into rows and columns.

 Absolute Layout : enables you to specify the exact location of its children.

 Frame Layout: is a placeholder on screen that you can use to display a single view.

 List View: is a view group that displays a list of scrollable items.

 Grid View: is a ViewGroup that displays items in a two-dimensional, scrollable


grid.

34
Cont’d

35
Common Attributes

36
Linear Layout
 LinearLayout is one of the simplest and most common layouts .
 A Layout that arranges its children in a single column or a single row.
 Available space is divided among layout children
 The direction of the row
android:orientation="vertical“
 You can also specify gravity, which specifies the
alignment of all the child elements using XML
android:gravity="center_horizontal“
 The default orientation is horizontal.

37
Linear Layout Attributes

38
Cont’d

39
Relative Layout
 RelativeLayout is a ViewGroup that displays child View elements in relative
positions.
 It is very powerful because it doesn’t require you to nest extra layouts to
achieve a certain look.
 The position of a View can be specified as relative to sibling elements (such as to
the left-of or below a given element) or in positions relative to the
RelativeLayout area (such as aligned to the bottom, left of center).

40
Cont’D

41
Table Layout
 TableLayout is a ViewGroup that displays child View elements in rows and
columns.
 Has a structure similar to an HTML table.
 The TableLayout element is like the HTML <table> element; TableRow is
like a <tr> element
 In each cell you can use any kind of View element arranged like columns with
horizontal linear layout.

42
Table Layout

43
Cont’d

44
Frame Layout
 FrameLayout places its children on top of each other so that the latest

child is covering the previous one

 FrameLayout is also used as a placeholder for other widgets that will be

added programmatically at some later point in time.

45
Defining Styles
 Multiple Buttons
 Define style only once!

46
Styles in values/styles.xml

47
Styles and Themes
 Way of building and formatting layout to your app

 Style has formatting attributes to several elements

 Theme has formatting attributes to all activities

Create the theme in xml (styles.xml)

Apply the theme in manifest

48
Building Layouts with Adapter
 When the content for your layout is dynamic or not pre-determined, you can
use a layout that subclasses AdapterView to populate the layout with views at
runtime.
 A subclass of the AdapterView class uses an Adapter to bind data to its layout.

 The Adapter behaves as a middleman between the data source and


the AdapterViewlayout—the Adapter retrieves the data (from a source such as
an array or a database query) and converts each entry into a view that can be
added into the AdapterView layout.
 Common layouts backed by an adapter include:
 List View : Displays a scrolling single column list.
 GridView: Displays a scrolling grid of columns and rows.

49
List View
 Android ListView is a view which groups several items and display them in
vertical scrollable list.
 The list items are automatically inserted to the list using an Adapter that pulls
content from a source such as an array or database.
 An adapter actually bridges between UI components and the data source that
fill data into UI Component.
 Adapter can be used to supply the data to like spinner, list view, grid view etc.
 The ListView and GridView are subclasses of AdapterView and they can be
populated by binding them to an Adapter, which retrieves data from an external
source and creates aView that represents each data entry.
 The two most common adapters are ArrayAdapter and
SimpleCursorAdapter.

50
Grid View
 Android GridView shows items in two-dimensional scrolling grid (rows
& columns) and the grid items are not necessarily predetermined
 An adapter actually bridges between UI components and the data source
that fill data into UI Component.
 Adapter can be used to supply the data to like spinner, list view, grid
view etc.
 The ListView and GridView are subclasses of AdapterView and they can
be populated by binding them to an Adapter, which retrieves data from
an external source and creates a View that represents each data entry.
 they automatically inserted to the layout using a ListAdapter

51
52
Part-II
Menus, Dialogues, Lists, Notifications and
Toasts

Mobile Application Development


Contents
 In this Section, you will learn about:

Menus

Dialogues

Lists

Notifications

Toasts
Menu
 Appear whenever the user presses the menu button.
 Useful for giving different options without leaving the current Activity
 Don’t make too big menus, or they’ll 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 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
 Displays a list of items in a vertical list that's anchored to the view that invoked the
menu.
55
Creating a Menu
 Two methods:
 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

56
Defining 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 XML menu resource then inflate the menu

resource (load it as a Menu object) 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 configurations for different platform

versions, screen sizes, and other configurations by leveraging the app


resources framework.
57
Cont’D
 To define the menu, create an XML file inside project's res/menu/ directory and

build the menu with the following elements:


 <menu>
 Defines a Menu, 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 a MenuItem, 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 properties such as active
state and visibility.

58
Cont’d

59
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.
 android:showAsAction
 Specifies when and how this item should appear as an action item in the action
bar.
60
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 into topics, like items in a PC application's menu bar (File, Edit, View,
etc.).
 For example:
To use the menu in activity, inflate the menu resource
using MenuInflater.inflate().

61
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, override onCreateOptionsMenu(). In
this method, you can inflate your menu resource (defined in XML) into
the Menu provided in the callback.
 For example:

You can also add menu items using add() and retrieve
items with findItem() to revise their properties with
MenuItem APIs.
62
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's onOptionsItemSelected() method, which
passes the MenuItem selected.
 You can identify the item by calling getItemId(), which returns the unique ID for the
menu item (defined by the android:id attribute in the menu resource or with an
integer given to the add() method).
 You can match this ID against known menu items to perform the appropriate action.

When you successfully handle a menu item, return true. If you don't handle the menu item, you
should call the superclass implementation of onOptionsItemSelected() (the default implementation
returns false).

63
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 a ListView, GridView, or other view collections in
which the user can perform direct actions on each item

64 Screenshots of a floating context menu (left) and the contextual action bar (right).
Cont’D
 There are two ways to provide contextual actions:
 In a floating 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 the contextual action mode. This mode is a system implementation of
ActionMode that displays a contextual action bar at 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).

65
Creating a floating context menu
To provide a floating context menu:
 Register the View to which the context menu should be associated by
calling registerForContextMenu() and pass it the View. If your activity uses
a ListView or GridView and you want each item to provide the same context
menu, register all items for a context menu by passing
the ListView or GridView to registerForContextMenu().
 Implement the onCreateContextMenu() method in your Activity. When the
registered view receives a long-click event, the system calls
your onCreateContextMenu() method. This is where you define the menu
items, usually by inflating a menu resource.
 MenuInflater allows you to inflate the context menu from a menu resource.
The callback method parameters include the View that the user selected and
a ContextMenu. ContextMenuInfo object that provides additional information
66 about the item selected.
Cont’d
 If your activity has several views that each provide a different context

menu, you might use these parameters to determine which context


menu to inflate.

67
IHandling click events
 Implement onContextItemSelected():
 When the user selects a menu item, the system calls this method so
you can perform the appropriate action.

68
Creating a Popup Menu
 A PopupMenu is a modal menu anchored to a View. 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 that relate to specific 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 to Spinner that does not retain a persistent
selection.
 If you define your menu in XML, here's how you can show the popup menu:

 Instantiate a PopupMenu with its constructor, which takes the current


application Context and the View to which the menu should be anchored.
 Use MenuInflater to inflate your menu resource into the Menu object returned
by using PopupMenu.inflate().
 Call PopupMenu.show().
69
Cont’D
 Example

70
Handling click events
 To perform an action when the user selects a menu item, you must implement the
PopupMenu.OnMenuItemClickListener interface and register it with
your PopupMenu by calling setOnMenuItemclickListener().
 When the user selects an item, the system calls the onMenuItemClick() callback in
your interface.

71
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 with setGroupVisible()
 Enable or disable all items with setGroupEnabled()
 Specify whether all items are checkable with setGroupCheckable()
 You can create a group by nesting <item> elements inside a <group> element in your
menu resource or by specifying a group ID with the add() method.

72
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:checkable attribute in the <item> element, or for an entire group with
the android:checkableBehavior attribute in the <group> element.

73
Cont’D
 The android:checkableBehavior attribute 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
the android:checked attribute in the <item> element and change it in code
with the setChecked() method.
 When a checkable item is selected, the system calls your respective item-
selected callback method (such as onOptionsItemSelected()).
 You can query the current state of the item (as it was before the user selected
it) with isChecked() and then set the checked state with setChecked().
74
Cont’D
 Example

75
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.

76
Cont’D
 The Dialog class 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.
DatePickerDialog or TimePickerDialog: 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
a DialogFragment as a container for your dialog. The DialogFragment class
provides all the controls you need to create your dialog and manage its
appearance, instead of calling methods on the Dialog object.
 Using DialogFragment to manage the dialog ensures that it correctly handles
lifecycle events such as when the user presses the Back button or rotates the
screen.
 The DialogFragment class also allows you to reuse the dialog's UI as an
embeddable component in a larger UI.

77
Creating a Dialog Fragment
 You can accomplish a wide variety of dialog designs by extending DialogFragment and
creating AlertDialog in the onCreateDialog() callback method.

78
Building an Alert Dialog
 The AlertDialog class 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.

79
Cont’D

80
Adding Buttons
 To add action buttons, call the setPositiveButton() and setNegativeButton() methods:

81
Cont’D
 The set...Button() methods require a title for the button (supplied by a string
resource) and a DialogInterface.OnClickListener that 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 an AlertDialog. That is, you cannot
have more than one "positive" button.

82
Adding a list
 There are three kinds of lists available with the AlertDialog APIs:
 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 the setItems() method:

83
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 setMultiChoiceItems() or setSingleChoiceItems() methods, 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 an ArrayList:

84
Notifications
 A notification is a message you can display to the user outside of your application's
normal UI.
 When you tell the system to issue a notification, it first appears as an icon in
the notification area.
 To see the details of the notification, the user opens the notification drawer.
 Both the notification area and the notification drawer are system-controlled areas that the
user can view at any time.

Figure 1. Notifications in the notification area.

Figure 2. Notifications in the notification drawer.


85
Notification Display Elements
 Notifications in the notification drawer can appear in one of two visual styles,
depending on the version and the state of the drawer:
 Normal view: The standard view of the notifications in the notification
drawer.
 Big view: A large view that's visible when the notification is expanded. Big
view is part of the expanded notification feature available as of Android 4.1.

86
Normal view
 A notification in normal view appears in an area that's up to 64 dp tall.
 Even if you create a notification with a big view style, it will appear in normal view
until it's expanded.
 An example of a normal view:

 The callouts in the illustration refer to the following:


1. Content title
2. Large icon
3. Content text
4. Content info
5. Small icon
6. Time that the notification was issued.
87
Big view
 A notification's big view appears only when the notification is expanded, which
happens when the notification is at the top of the notification drawer, or when the user
expands the notification with a gesture.
 Expanded notifications are available starting with Android 4.1.
 The following screenshot shows an inbox-style notification:

Figure 4. Big view notification.


88
Cont’D
 Notice that the big view shares most of its visual elements with the normal
view.
 The only difference is callout number 7, the details area. Each big view style
sets this area in a different way.
 The available styles are:
Big picture style: The details area contains a bitmap up to 256 dp tall
in its detail section.
Big text style: Displays a large text block in the details section.
Inbox style: Displays lines of text in the details section.
 All of the big view styles also have the following content options that aren't
available in normal view:
 Big content title: Allows you to override the normal view's content title
with a title that appears only in the expanded view.
 Summary text: Allows you to add a line of text below the details area.
89
Creating a Notification
 Notification in android are represented by the Notification class.
 To create notification use NotificationManager class which can be received from the
Context, e.g. an activity or a service, via GetSystemService() method.
 The Notification.Builder provides a builder interface to create a Notification object
 PendingIntent to specify the action which should be performed once the user select
the notification.
Required notification contents
 A Notification object must contain the following:
 A small icon, set by setSmallIcon()
 A title, set by setContentTitle()
 Detail text, set by setContentText()

90
Cont’D
 The Notification.Builder provides a builder interface to create a Notification object

91
Managing Notifications
 When you need to issue a notification multiple times for the same type
of event, you should avoid making a completely new notification.
 Instead, you should consider updating a previous notification, either by
changing some of its values or by adding to it, or both.
 For example, Gmail notifies the user that new emails have arrived by
increasing its count of unread messages and by adding a summary of each
email to the notification.

92
Removing notifications
 Notifications remain visible until one of the following happens:
 The user dismisses the notification either individually or by using "Clear All" (if the
notification can be cleared).
 The user clicks the notification, and you called setAutoCancel() when you created
the notification.
 You call cancel() for a specific notification ID. This method also deletes ongoing
notifications.
 You call cancelAll(), which removes all of the notifications you previously issued.

93
Toasts
 A toast provides simple feedback about an operation in a small popup.
 It only fills the amount of space required for the message and the current activity
remains visible and interactive.
 Toasts automatically disappear after a timeout.
 For example, navigating away from an email before you send it triggers a "Draft saved"
toast to let you know that you can continue editing later.

94
The Basics
 First, instantiate a Toast object with one of the makeText() methods.
 This method takes three parameters: the application Context, the text message, and
the duration for the toast.
 It returns a properly initialized Toast object.
 You can display the toast notification with show(), as shown in the following example:

95
Positioning your Toast
 A standard toast notification appears near the bottom of the screen, centered
horizontally.
 You can change this position with the setGravity(int, int, int) method.
 This accepts three parameters: a Gravity constant, an x-position offset, and a y-
position offset.
 For example, if you decide that the toast should appear in the top-left corner, you can
set the gravity like this:

 If you want to nudge the position to the right, increase the value of the second
parameter.To nudge it down, increase the value of the last parameter.

96
97

You might also like