Você está na página 1de 60

Mobile Application Development in

Android
Bangladesh-Korea Information Access Center (IAC)
Department of Computer Science and Engineering (CSE)
Bangladesh University of Engineering and Technology (BUET)
E-mail: eunus@cse.buet.ac.bd
USER INTERFACES
Prelude
Android runs on a variety of devices that offer
different screen sizes and densities
The Android system provides
A consistent development environment across devices
Handles most of the work to adjust each application's user
interface to the screen on which it is displayed.
APIs that allow you to control your application's UI for specific
screen sizes and densities, in order to optimize your UI design
for different screen configurations.
Although the system performs scaling and resizing
to make your application work on different screens,
you should make the effort to optimize your
application for different screen sizes and densities.

Eunus/CSE/BUET
Terms and Concepts
Screen size
Actual physical size, measured as the screen's diagonal.
For simplicity, Android groups all actual screen sizes into four
generalized sizes: small, normal, large, and extra large.
Screen density
The quantity of pixels within a physical area of the screen;
usually referred to as dpi (dots per inch).
For example, a "low" density screen has fewer pixels within a
given physical area, compared to a "normal" or "high" density
screen.
For simplicity, Android groups all actual screen densities into four
generalized densities: low, medium, high, and extra high.

Eunus/CSE/BUET
Terms and Concepts
Orientation
The orientation of the screen from the user's point of view.
This is either landscape or portrait, meaning that the screen's
aspect ratio is either wide or tall, respectively.
The orientation can change at runtime when the user rotates the
device.
Resolution
The total number of physical pixels on a screen.
When adding support for multiple screens, applications do not
work directly with resolution; applications should be concerned
only with screen size and density, as specified by the
generalized size and density groups.
Eunus/CSE/BUET
Terms and Concepts
Density-independent pixel (dp)
A virtual pixel unit that you should use when defining UI layout, to
express layout dimensions or position in a density-independent way.
The density-independent pixel is equivalent to one physical pixel on
a 160 dpi screen, which is the baseline density assumed by the
system for a "medium" density screen.
At runtime, the system transparently handles any scaling of the dp
units, as necessary, based on the actual density of the screen in
use.
The conversion of dp units to screen pixels is simple: px = dp * (dpi /
160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical
pixels.
You should always use dp units when defining your application's UI,
to ensure proper display of your UI on screens with different
densities.

Eunus/CSE/BUET
Range of Screen Supported
To simplify the way that you design your user interfaces
for multiple screens, Android divides the range of actual
screen sizes and densities into:
A set of four generalized sizes: small, normal, large, and xlarge
A set of four generalized densities: ldpi (low), mdpi (medium), hdpi
(high), and xhdpi (extra high)
The generalized sizes and densities are arranged around
a baseline configuration that is a normal size and mdpi
(medium) density.
Each generalized size and density spans a range of
actual screen sizes and densities
Eunus/CSE/BUET
Optimizing UI for Different Devices
To optimize your application's UI for the different
screen sizes and densities,
You can provide alternative resources for any of the generalized
sizes and densities.
Typically, you should provide alternative layouts for some of the
different screen sizes and alternative bitmap images for different
screen densities.
At runtime, the system uses the appropriate resources for your
application, based on the generalized size or density of the
current device screen.
Eunus/CSE/BUET
Providing Alternative Resources
To specify configuration-specific alternatives for a
set of resources:
Create a new directory in res/ named in the form
<resources_name>-<config_qualifier>.
<resources_name> is the directory name of the
corresponding default resources (defined in table 1).
<qualifier> is a name that specifies an individual
configuration for which these resources are to be used
You can append more than one <qualifier>. Separate each one
with a dash.

Eunus/CSE/BUET
Providing Alternative Resources
Save the respective alternative resources in this new
directory.
The resource files must be named exactly the same
as the default resource files.
Example
res/ drawable/
icon.png
background.png
drawable-hdpi/
icon.png
background.png
The hdpi qualifier indicates that the resources in that directory
are for devices with a high-density screen.
Eunus/CSE/BUET
Qualifiers Name
When appending
multiple qualifiers, you
must place them in the
same order in which
they are listed in this
table. If the qualifiers
are ordered wrong, the
resources are ignored.
Eunus/CSE/BUET
Configuration Qualifier Values
Screen size small
normal
large
xlarge
Screen aspect long
notlong
Screen orientation port
land
Screen pixel density (dpi) ldpi
mdpi
hdpi
xhdpi
Density Independence
Your application achieves "density independence"
when it preserves the physical size (from the user's
point of view) of user interface elements when
displayed on screens with different densities.
Maintaining density independence is important
because, without it, a UI element (such as a button)
appears physically larger on a low density screen
and smaller on a high density screen


Eunus/CSE/BUET
Density Independence
Eunus/CSE/BUET
Figure: Without support for different
densities
Figure: With support for different densities
The Android system helps your application achieve
density independence in two ways:
The system scales dp units as appropriate for the current screen
density
The system scales drawable resources to the appropriate size,
based on the current screen density, if necessary

Eunus/CSE/BUET
Density Independence
How to Support Multiple Screens
Explicitly declare in the manifest which screen sizes
your application supports
Provide different layouts for different screen sizes
Provide different bitmap drawables for different
screen densities
Eunus/CSE/BUET
Selecting the resources at Run time
At run time, the system ensures the best possible
display on the current screen with the following
procedure for any given resource:
1. The system uses the appropriate alternative resource
2. If no matching resource is available, the system uses the
default resource and scales it up or down as needed to match
the current screen size and density
The "default" resources are those that are not
tagged with a configuration qualifiers
Eunus/CSE/BUET
Thumb Rule for selecting drawable
Eunus/CSE/BUET
For example, if you have a
bitmap drawable that's 48x48
pixels for medium-density
screen (the size for a launcher
icon), all the different sizes
should be:
36x36 for low-density
48x48 for medium-density
72x72 for high-density
96x96 for extra high-density

The View Class
View class represents the basic block for user
interface components.
Each View occupies a rectangular area on the
screen and is responsible for drawing (drawing) and
event handling (event handlers).
View is the base class for widgets, used to create
the interactive component of the UI (buttons, text
fields, etc.).
ViewGroup subclass is the base class for all layout
(layout), is the invisible container that contains the
View (or ViewGroup) and other provisions of the
characteristics of their composition.

View
All of view in a window is organized in a tree
structure.
We can add the view from the source or definition of
the view tree structure in one or more XML layout
file.

19
After creating a View
Set properties: for example assign text in a TextView
available. The property that previously could be built
in the XML layout file.
Set focus: focus mechanism movement in response
to user input. To view requirements for a specific
focus, call requestFocus ().
Set up listeners: View lets put the listener, the
listener is invoked when an event occurs for the
view.
Button using an event listener to hear the button is
clicked.
Set visibility: You can hide or show the view by
setVisibility (int).

20
A brief sample of UI components
21
Linear Layout
A LinearLayout is a
GroupView that will lay
child View elements
vertically or horizontally.
Relative Layout
A RelativeLayout is a ViewGroup
that allows you to layout child
elements in positions relative to
the parent or siblings elements.
Table Layout
A TableLayout is a
ViewGroup that will lay
child View elements into
rows and columns.
A brief sample of UI components
22
DatePicker
A DatePicke is a widget
that allows the user to
select a month, day and
year.
Form Controls
Includes a variety of typical
form widgets, like:
image buttons,
text fields,
checkboxes and
radio buttons.
GalleryView

TabWidget


Spinner
A brief sample of UI components
23
AutoCompleteTextView
It is a version of the EditText
widget that will provide
auto-complete suggestions
as the user types. The
suggestions are extracted
from a collection of strings.
ListView
A ListView is a View that
shows items in a vertically
scrolling list. The items are
acquired from a ListAdapter.
WebView
MapView
What is an XML Layout?
24
XML-based layout is a specification of the UI components
(widgets), the relationship between them and the container
containing them - all are written in XML format.
Android as the XML-
based layout is the
resource (resource),
and the layout file is
saved in the folder
res/layout of our
project.
What is an XML Layout?
Each XML file contains a hierarchical tree structure,
specification and layout of the container widget
component of a View.
The properties of each XML element is the nature
and describe the appearance of the widget or the
operation of a container.
Example:
If a Button element with an attribute value
android: textStyle = "bold"
This means that the text on the button should be
drawn with bold font (bold).

25
An example
26
import java.util.Date;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class AndDemo extends Activity {
Button btn;

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.myButton);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
updateTime();
}
});
}// onCreate
//
private void updateTime() {
btn.setText(new Date().toString());
}

}
An example
27
This is the XML-Layout definition
<?xml version="1.0" encoding="utf-8"?>
<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myButton"
android:text=""
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
The root element (root) to Android XML namespace declarations:
xmlns:android = http://schemas.android.com/apk/res/android
All other elements are children of the root and will inherit that namespace
declaration.
Because we want to call it button from within Java code, we need to give
it an id attribute via android: id.
An example cont.
28
<?xml version="1.0" encoding="utf-8"?>
<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myButton"
android:text=""
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
The remaining attributes of the entity Button are:
android:text initial value of the string to the current text on the buttons
(here is the empty string)
android:layout_width and android:layout_height tell that the width and
height of the buttons occupy the entire container (parent), here is the
entire screen.
UI Hierarchy
29
The utility HierarchyViewer displays the UI structure of the current screen
shown on the emulator or device.

( Execute app on emulator, execute HierarchyViewer, click on Emulator >
Refresh Screenshot )
UI
Tree
Look for your SDK folder, usually:
C:/your_sdk_path/android_sdk_windows/tools
Android Layouts
30
Each element in the XML Layout is either a View or ViewGroup object
Android Layouts
Displaying the Applications View
The Android UI Framework paints the screen by walking the View tree
by asking each component to draw itself in a pre-order traversal way.
Each component draws itself and then asks each of its children to do
the same.


31
Android Layouts
32
Example: Display UI Hierarchy
vertical
Horizontal 1
Horizontal 2
Using SDK
older than r8.
Android Layouts
33
Example: Display UI Hierarchy
vertical
Horizontal 1
Horizontal 2
UI
Tree
Example: Display UI Hierarchy
34
See: Android Application Development, by R. Rogers et al. OReilly Pub. 2009, ISBN 978-0-596-52147-0
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout android:id="@+id/LinearLayout02"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<EditText android:id="@+id/txtXcoord" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="X Coord"
android:layout_weight="1">
</EditText>
<EditText android:id="@+id/edtYcoord" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Y Coord"
android:layout_weight="1">
</EditText>
</LinearLayout>
<LinearLayout android:id="@+id/LinearLayout03"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<Button android:id="@+id/btnRed" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="red"
android:layout_weight="1">
</Button>
<Button android:id="@+id/btnGreen" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="green"
android:layout_weight="1">
</Button>
</LinearLayout>
</LinearLayout>

Common Layouts
There are five basic types of Layouts
Frame,
Linear
Relative
Table
Absolute.


35
Common Layouts: FrameLayout
FrameLayout is the simplest type of layout object.
It's basically a blank space on your screen that you can later
fill with a single object for example, a picture that you'll
swap in and out.
All child elements of the FrameLayout are pinned to the top
left corner of the screen; you cannot specify a different
location for a child view.
Subsequent child views will simply be drawn over previous
ones, partially or totally obscuring them (unless the newer
object is transparent).


36
Common Layouts: LinearLayout
LinearLayout aligns all children in a single direction
vertically or horizontally depending on the
android:orientation attribute.
All children are stacked one after the other
vertical list will only have one child per row, no matter how wide they
are
horizontal list will only be one row high (the height of the tallest
child, plus padding).
A LinearLayout respects margins between children and the
gravity (right, center, or left alignment) of each child.


37
38
You may attribute a weight to children of a LinearLayout.
Weight gives an "importance" value to a view, and allows it to expand to fill any remaining
space in the parent view.
Example:
The following two forms represent a LinearLayout
with a set of elements: a button, some labels and
text boxes. The text boxes have their width set to
fill_parent; other elements are set to wrap_content.
The gravity, by default, is left.

The difference between the two versions of the
form is that the form on the left has weight values
unset (0 by default), while the form on the right has
the comments text box weight set to 1. If the Name
textbox had also been set to 1, the Name and
Comments text boxes would be the same height.
Common Layouts: LinearLayout
Common Layouts: TableLayout
TableLayout positions its children into rows and
columns.
TableLayout containers do not display border lines.
The table will have as many columns as the row with
the most cells.
A cell could be empty, but cannot span columns, as
they can in HTML.
A TableRow object defines a single row in the table.
A row has zero or more cells, each cell is defined by
any kind of other View.
A cell may also be a ViewGroup object.


39
Common Layouts: TableLayout

40
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="*">
<TableRow>
<TextView android:text="Open"
android:padding="3dip" />
<TextView android:text="Ctrl-O"
android:gravity="right"
android:padding="3dip" />
</TableRow>
<TableRow>
<TextView android:text="Save As"
android:padding="3dip" />
<TextView android:text="Ctrl-Shift-S"
android:gravity="right"
android:padding="3dip" />
</TableRow>
</TableLayout>
TableLayout Example
The following sample layout has
two rows and two cells in each.
The accompanying screenshot
shows the result, with cell
borders displayed as dotted
lines (added for visual effect).
RelativeLayout lets child views specify their position relative
to the parent view or to each other (specified by ID).
You can align two elements by right border, or make one
below another, centered in the screen, centered left, and so
on.
Elements are rendered in the order given, so if the first
element is centered in the screen, other elements aligning
themselves to that element will be aligned relative to screen
center.
Also, because of this ordering, if using XML to specify this
layout, the element that you will reference (in order to
position other view objects) must be listed in the XML file
before you refer to it from the other views via its reference
ID.

41
Common Layouts: RelativeLayout
For example, assigning the parameter

android:layout_toLeftOf=@+id/my_button"
to a TextView would place the TextView to the left of the View with the ID my_button

The defined RelativeLayout parameters are (android:layout_...)
:

width, height,
below, above
alignTop, alignParentTop,
alignBottom, alignParentBottom
toLeftOf, toRightOf

padding [Bottom|Left|Right|Top], and
margin [Bottom|Left|Right|Top].


42
Common Layouts: RelativeLayout

43
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff0000ff"
android:padding="10px" >

<TextView android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffff0077"
android:text="Type here:" />

<EditText android:id="@+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/label" />

RelativeLayout Example

The example below shows an XML file
and the resulting screen in the UI. Note
that the attributes that refer to relative
elements (e.g., layout_toLeft) refer to
the ID using the syntax of a relative
resource (@+id/id).
Continue next page
Common Layouts: RelativeLayout
44

<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/entry"
android:layout_alignParentRight="true"
android:layout_marginLeft="10px"
android:text="OK" />

<Button
android:text="Cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/ok"
android:layout_alignTop="@+id/ok />

</RelativeLayout>

RelativeLayout Example
Cont.
Common Layouts: RelativeLayout
AbsoluteLayout that lets you specify exact locations (x/y
coordinates) of its children.
AbsoluteLayouts are less flexible and harder to maintain
than other types of layouts without absolute positioning.
Common Layouts: AbsoluteLayout
Attaching Layouts to Java Code
46
Plumbing. We have to 'connect' with parts of objects from XML equivalent
in activity. Thus, we can manipulate the UI from program code.
XLM Layout
<xml.
. . .
. . .
</xml>

JAVA code
public class .
{
. . .
. . .
}
Suppose UI was created in res / layout / main.xml.
Applications can call this layout with the command
setContentView(R.layout.main);
Can access the widget, such myButton, findViewByID
command (...) as follows
Button btn = (Button)
findViewByID(R.id.myButton);
In particular, R is an automatically generated class to track
the application's resources. Specifically, R.id. .. the widget is
defined in the XML layout

47
Attaching Layouts to Java Code
Attach Listener to Widget (event handling)
Button in your example you can use after you add a listener for the
click event:

48
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
updateTime();
}
});

private void updateTime() {
btn.setText(new Date().toString());
}
Attaching Layouts to Java Code
Basic Widgets: TextView
A label is called in android a
TextView.
TextViews are typically used
to display a caption.
TextViews are not editable,
therefore they take no input.
49
Basic Widgets: TextView
50
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/myLinearLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:id="@+id/myTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ff0000ff"
android:padding="3dp"
android:text="Enter User Name"
android:textSize="16sp"
android:textStyle="bold"
android:gravity="center">
</TextView>

</LinearLayout>
Basic Widgets: Buttons
A Button widget allows the simulation of a clicking action on a
GUI.
Button is a subclass of TextView. Therefore formatting a Buttons
face is similar to the setting of a TextView.

51
...
<Button
android:id="@+id/btnExitApp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10px"
android:layout_marginLeft="5px"
android:text="Exit Application"
android:textSize="16sp"
android:textStyle="bold"
android:gravity="center"
android:layout_gravity="center_horizontal"
>
</Button>
Basic Widgets: Images
ImageView and ImageButton are two Android widgets that
allow embedding of images in your applications.
Both are image-based widgets analogue to TextView and
Button, respectively.
Each widget takes an android:src or
android:background attribute (in an XML layout) to
specify what picture to use.
Pictures are usually reference a drawable resource.
ImageButton, is a subclass of ImageView. It adds the
standard Button behavior for responding to click events.
52
Basic Widgets: Images

53
...
<ImageButton
android:id="@+id/myImageBtn1"
android:src="@drawable/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</ImageButton>
<ImageView
android:id="@+id/myImageView1"
android:src="@drawable/microsoft_sunset"
android:layout_width="150px"
android:layout_height="120px"
android:scaleType="fitXY"
>
</ImageView>

Basic Widgets: EditText
The EditText widget is an
extension of TextView that
allows updates.
The control configures
itself to be editable.
Important Java methods
are:
txtBox.setText(someValue)
txtBox.getText().toString()

54
In addition to the standard TextView
properties EditText has many others features
such as:
android:autoText, (true/false) provides automatic spelling assistance
android:capitalize, (words/sentences) automatic capitalization
android:digits, to configure the field to accept only certain digits
android:singleLine, is the field for single-line / multiple-line input
android:password, (true/false) controls fields visibility
android:numeric, (integer, decimal, signed) controls numeric format
android:phonenumber, (true/false) Formatting phone numbers



55
Basic Widgets: EditText
56
Example

...
<EditText
android:id="@+id/txtUserName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:autoText="true"
android:capitalize="words"
android:hint="First Last Name"
>
</EditText>
...
Upper case words
Enter teh
It will be changed to: The
Suggestion (grey)
Basic Widgets: EditText
Basic Widgets: CheckBox
A checkbox is a specific type of
two-states button that can be
either checked or unchecked.
A example usage of a checkbox
inside your activity would be the
following:

57
...
<CheckBox
android:id="@+id/chkName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=Sugar"
android:textStyle=bold"
>
</CheckBox>
...
Basic Widgets: RadioButtons
A radio button is a two-states button that can be either checked or
unchecked.
When the radio button is unchecked, the user can press or click it
to check it.
Radio buttons are normally used together in a RadioGroup.
When several radio buttons live inside a radio group, checking one
radio button unchecks all the others.
RadioButton inherits from TextView. Hence, all the standard
TextView properties for font face, style, color, etc. are available for
controlling the look of radio buttons.
Similarly, you can call isChecked() on a RadioButton to see if it is
selected, toggle() to select it, and so on, like you can with a
CheckBox.

58
Basic Widgets: RadioButtons
59
...
<RadioGroup
android:layout_width="fill_parent"

android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/radio_group1">
<RadioButton
android:id="@+id/radDecaf"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Decaf"
>
</RadioButton>
.
</RadioGroup>

...
RadioGroup
Getting Radiobutton Value
// Gets a reference to our radio group
// rBtnDigits is the name of our radio group (code not
shown)
RadioGroup g = (RadioGroup)
findViewById(R.id.rBtnDigits);
// Returns an integer which represents the selected radio
button's ID
int selected = g.getCheckedRadioButtonId();
// Gets a reference to our "selected" radio button
RadioButton b = (RadioButton) findViewById(selected);
// Now you can get the text or whatever you want from the
"selected" radio button
b.getText();

Eunus/CSE/BUET

Você também pode gostar