CH Two
CH Two
XML Basics
Android Layouts
XML Basics
It stands for eXtensible Markup Language (ML).
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
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
DTD defines the structure and the legal elements and attributes of an XML
document
a DTD
XML Schema describes the structure of an XML document, just like a DTD
An XML document validated against an XML Schema is both "Well Formed" and
"Valid"
Cont’D
Cont’D
Cont’D
Description of 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.
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
They are quite different but often are used together to get the job done.
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
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.
If you have prior experience with Java Swing, layouts are similar to Java
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
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.
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
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
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.
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
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
It separates the content for the menu from application's behavioral code.
58
Cont’d
59
The <item> element
The <item> element supports several attributes you can use to define an item's
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
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:
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.
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:
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