0% found this document useful (0 votes)
6 views

Week 4

Uploaded by

justmquan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Week 4

Uploaded by

justmquan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Lesson 4

Lesson 4

Graphical User Interfaces

Victor Matos
Cleveland State University

Notes are based on:


The B
Th Busy C
Coder's
d ' GGuide
id tto A
Android
d id DDevelopment
l t
by Mark L. Murphy
Copyright © 2008‐2009 CommonsWare, LLC.
ISBN: 978‐0‐9816780‐0‐9
&
Android Developers
http://developer.android.com/index.html

Portions of this page are reproduced from work created and shared by Google and used according to terms
described in the Creative Commons 3.0 Attribution License.

The Model‐View‐Control (MVC) Pattern


The Model‐View‐Controller (MVC) is an
important software design pattern whose
main goal is to separate the (1) user
interface (2) business
interface, business, and (3) input logic
logic.

How is this seen by the Android developer?

• Model. Consists of the Java code and objects used to manage the behavior
and data of the application.
• View. Set of screens the user sees and interacts with.
• Controller. Implemented through the Android OS, responsible for
interpretation of the user and system inputs. Input may come from a variety
of sources such as the trackball, keyboard, touchscreen, GPS chip,
background services, etc, and tells the Model and/or the View (usually
through callbacks and registered listeners) to change as appropriate.

[Burbeck92] Burbeck, Steve. "Application Programming in Smalltalk‐80: How to use Model‐View‐Controller (MVC)."University of Illinois
in Urbana‐Champaign (UIUC) Smalltalk Archive. Available at: http://st‐www.cs.illinois.edu/users/smarch/st‐docs/mvc.html.
2
Lesson 4

Android & the MVC Pattern


The View ‐ User Interfaces (Uis)
Android graphical interfaces are usually implemented as XML files (although
they could also be dynamically created from code).

An Android UI is conceptually similar to a common HTML page

• In a manner similar to a web page interaction, when the Android user


touches the screen, the controller interprets the input and determines
what specific portion of the screen and gestures were involved. Based on
this information it tells the model about the interaction in such a way
that the appropriate “callback listener” or lifecycle state could be called
into action.

• Unlike a web application (which refreshes its pages after explicit


requests from the user) an asynchronous Android background service
could quietly notify the controller about some change of state (such as
reaching a given coordinate on a map) and in turn a change of the view’s
state could be triggered; all of these without user intervention.
4
Lesson 4

UI Design Patterns
For a detailed discussion on Android UI Design Patterns see video:
http://www.youtube.com/watch?v=M1ZBjlCRfz0&feature=player_embedded

The View Class


• The View class is the Android’s most basic component from which users interfaces
can be created. This element is similar to the Swing JComponent class for Java apps.

• A View occupies a rectangular area on the screen and is


responsible for drawing and event handling.

• Widgets are subclasses of View. They are used to create


interactive UI components such as buttons, checkboxes,
labels, text fields, etc.

• Layouts are invisible containers used for holding other


Views and nested layouts
layouts.

6
Lesson 4

Graphical UI ↔ XML Layout


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:hint="Enter you name here"
android:layout_marginTop="50dp"
android:ems="10" >

<requestFocus />
</EditText>

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout below="@+id/editText1"
android:layout_below= @+id/editText1
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:text=" Go " />

</RelativeLayout>

Actual UI displayed by the app Text version: activity_main.xml file

Using Views
• An Android’s XML view file consists of a layout holding a hierarchical
arrangement of its contained elements.
• The inner elements could be simple widgets or nested layouts holding
some complex viewgroups.
• An Activity uses the setContentView(R.layout.xmlfilename)
method to render a view on the device’s screen.

<?xml version="1.0" encoding="utf‐8"?>


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >

Widgets and other nested layouts

</LinearLayout>

8
Lesson 4

Using Views
Dealing with widgets & layouts typically involves the following
operations

1. Set properties: For example setting the background color, text, font
and size of a TextView.

2. Set up listeners: For example, an image could be programmed to


respond to various events such as: click, long‐tap, mouse‐over, etc.

3. Set focus: To set focus on a specific view, you call the method
requestFocus() or use XML tag <requestFocus />

4. Set visibility: You can hide or show views using setVisibility(…).

A brief sample of UI components


Layouts

Linear Layout Relative Layout Table Layout


A LinearLayout places its A RelativeLayout is a ViewGroup A TableLayout is a
inner views either in that allows you to position ViewGroup that places
horizontal or vertical elements relative to each other. elements using a row &
disposition. column disposition.
Reference: http://developer.android.com/guide/topics/ui/layout‐objects.html
10
Lesson 4

A brief sample of UI components


Widgets

GalleryView

TabWidget

Spinner

TimePicker Form Controls


AnalogClock Includes a variety of typical
DatePicker form widgets, like:
A DatePicke is a widget image buttons,
that allows the user to text fields,
select a month, day and checkboxes and
year. radio buttons.
Reference: http://developer.android.com/guide/topics/ui/layout‐objects.html
11

A brief sample of UI components


WebView

MapView

AutoCompleteTextView ListView
It is a version of the EditText A ListView is a View that
widget that will provide shows items in a vertically
auto‐complete suggestions scrolling list. The items are
as the user types. The acquired from a ListAdapter.
suggestions are extracted
from a collection of strings.

Reference: http://developer.android.com/guide/topics/ui/layout‐objects.html
12
Lesson 4

XML Layouts
Android considers XML‐based layouts to be resources, consequently layout
files are stored in the res/layout directory inside your Android project.

XML version
of a window

13
Lesson 4

Tools for Android UI/XML Design

ASIDE ‐ CREATING ANDROID UI & APPS

You could create Layout XML files using UI tools such as:

• Wondershare Mockitt

• Sketch is an easy to use Android UI design software

• Marvel is a tool that makes it easy for designers to create

More on this issue later…


15

How to create complex UIs?


• The LinearLayout is arguably the most common type of container.
• It offers a "box" model where inner elements could be placed side‐by‐
side or up‐and‐down.
• In ggeneral,, complex
p UI designs
g could be made byy combiningg simplerp
nested boxes and stacking them in either a horizontal or vertical
orientation.

16
Lesson 4

Common Layouts
We will discuss the following common and useful layouts:
F
Frame, Linear,
Li R l tive, TTable,
Relati bl Constraint,
d Ab l tCoordinator

1. FrameLayout
• FrameLayout is the simplest type of layout.
• Useful as outermost container holding a window.
• Allows you to define how much of the screen (high,
width) is to be used.
used
• All its children elements are aligned to the top left corner
of the screen.;
17

1. FrameLayout
The android:layout_gravity attribute is used
to locate the child View(s)

18
Lesson 4

1. FrameLayout

The LinearLayout

2. Linear Layout

The widgets
Th id t or inner
i containers
t i h ld in
held i a LinearLayout
Li L t are
collocated one next to the other in either a column or a row.

Configuring a LinearLayout usually requires you to set the following


attributes:
• orientation,
• fill model,
model
• weight,
• gravity,
• padding ,
• margin
18
Lesson 4

The LinearLayout

2. Linear Layout

Orientation
The android:orientation property can be set to the
values: horizontal for rows or vertical for columns.

android:orientation="horizontal"

android:orientation="vertical"

The orientation can be modified at runtime by


invoking setOrientation()

19

The LinearLayout ‐ Orientation


2.1 Linear Layout: Orientation <?xml version="1.0" encoding="utf‐8"?>
<LinearLayout
android:id="@+id/myLinearLayout"
android:layout_width="fill_parent"
horizontal android:layout_height="fill_parent"
android:background="#ff0033cc"
android:padding="4dip"
xmlns:android="http://schemas.android.com/apk/res/android"
// / / /
android:orientation="horizontal" >
<TextView
android:id="@+id/labelUserName"
android:layout_width="wrap_content"
v android:layout_height="wrap_content"
e android:background="#ffff0066"
r android:text="User Name"
android:textSize="16sp"
t android:textStyle="bold"
i android:textColor="#ff000000" />
c <EditText
a android:id="@+id/ediName"
l android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp" />

<Button
android:id="@+id/btnGo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go"
android:textStyle="bold" />

</LinearLayout>

20
Lesson 4

The LinearLayout – Fill Model

2.2 Linear Layout: Fill Model


• Widgets have a "natural" size based on their included text.
• You may want to specify how tall & wide a widget should be even if no text is
i l d ((as iis th
involved the case off th
the empty
t ttextt b
box shown
h b
below).
l )

natural sizes
empty screen space

21

The LinearLayout – Fill Model

2.2 Linear Layout: Fill Model

All widgets inside a LinearLayout must include ‘width’ and ‘height’ attributes to
establish the issue of empty space around them.

android:layout_width
android:layout_height

Values used in defining height and width can be:


1. A specific dimension such as 125dip (device independent pixels, a.k.a. dp )
2. wrap_content indicates the widget should just fill up its natural space (if it is
too big other options such as word‐wrap could be used to make it fit).
3. match_parent (previously called ‘fill_parent’) indicates the widget wants to
be as big as the enclosing parent.

22
Lesson 4

The LinearLayout – Fill Model


<?xml version="1.0" encoding="utf‐8"?>
<LinearLayout
android:id="@+id/myLinearLayout"
android:layout_width="fill_parent"
2.2 Linear Layout: Fill Model android:layout_height="fill_parent"
android:orientation="vertical" Row‐wise
android:background="#ff0033cc"
125 dip android:padding="4dip"
xmlns:android="http://schemas.android.com/apk/res/android"
p // / p / /
entire row
(320 dpi on medium resolution screens) >
<TextView
android:id="@+id/labelUserName"
android:layout_width="fill_parent"
Use all the row
android:layout_height="wrap_content"
android:background="#ffff0066"
android:text="User Name"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="#ff000000" />

<EditText
android:id="@+id/ediName"
android:layout width="fill
android:layout_width= fill_parent
parent"
android:layout_height="wrap_content"
android:textSize="18sp" />

<Button
android:id="@+id/btnGo"
Specific size: 125dip
android:layout_width="125dip"
android:layout_height="wrap_content"
android:text="Go"
android:textStyle="bold" />

</LinearLayout>
Medium resolution is: 320 x 480 dpi. 23

The LinearLayout – Weight

2.3 Linear Layout: Weight


Indicates how much of the extra space in the LinearLayout will be allocated to the
view. Use 0 if the view should not be stretched. The bigger the weight the larger
th extra
the t space given
i tto th
thatt widget.
id t

Example
The XML specification for the window is
very similar to the previous example.

The TextView and Button controls have


the additional property
android:layout_weight="1" Takes: 2 /(1+1+2)
of the screen space

whereas the EditText control has


android:layout_weight="2"

Default value is 0
24
Lesson 4

The LinearLayout – Gravity

4.4 Layout_Gravity
• It is used to indicate how a control will align on the screen.
• By default, widgets are left‐ and top‐aligned.
• You may use the XML property
android:layout_gravity=“…”
to set other possible arrangements:
left, center, right, top, bottom, etc.
Button has
right
layout_gravity

25

The LinearLayout – Gravity

2.4 CAUTION: gravity vs. layout_gravity

The difference between:

android:gravity
indicates how to place an object within a container. In the example
the text is centered android:gravity="center"

android:layout_gravity
positions the view with respect to its
android:layout_gravity="center"

26
Lesson 4

The LinearLayout – Padding

2.5 Linear Layout: Padding

• The p
paddingg specifies
p how much extra space
p there is between the
boundaries of the widget's "cell" and the actual widget contents.

• Either use
• android:padding property
• or call method setPadding() at runtime.

27

The LinearLayout – Padding

Linear Layout: Padding and Marging

28
Lesson 4

The LinearLayout – Padding


Linear Layout: Internal Margins Using Padding

Example:
The EditText box has been changed to display 30dip of padding all around

<EditText
android:id="@+id/ediName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="30dip"

>
</EditText>
...

29

The LinearLayout – Margin


2.6 Linear Layout: (External) Margin
• Widgets –by default– are tightly packed next to each other.
• To increase space between them use the android:layout_margin attribute

Increased inter‐widget space

<EditText
android:id="@+id/ediName"
android:layout width="fill
android:layout_width fill_parent
parent"
android:layout_height="wrap_content"
android:textSize="18sp"

android:layout_margin="6dip"

>
</EditText>
...

30
Lesson 4

The Relative Layout

3. Relative Layout

The placement of widgets in a RelativeLayout is based on their positional


relationship to other widgets in the container and the parent container.

Example:
A A is by the parent’s top
C is below A, to its right
B is below A, to the left of C

B C

31

The Relative Layout

3. Relative Layout ‐ Referring to the container


Below there is a list of some positioning XML boolean properties (true/false)
mapping a widget according to its location respect to the parent’s
parent s place.

• android:layout_alignParentTop the widget's top should align with the top of the container.
• android:layout_alignParentBottom the widget's bottom should align with the bottom of the
container
• android:layout_alignParentLeft the widget's left side should align with the left side of the
container
• android:layout_alignParentRight the widget's right side should align with the right side of
the container

• android:layout_centerInParent the widget should be positioned both horizontally and


vertically at the center of the container
• android:layout_centerHorizontal the widget should be positioned horizontally at the center
of the container
• android:layout_centerVertical the widget should be positioned vertically at the center of the
container

32
Lesson 4

The Relative Layout

3. Relative Layout – Referring to other widgets

The following properties manage positioning of a widget respect to other


widgets:

• android:layout_above indicates that the widget should be placed above the


widget referenced in the property
• android:layout_below indicates that the widget should be placed below the
widget referenced in the property
• android:layout_toLeftOf
android:layout toLeftOf indicates that the widget should be placed to the left
of the widget referenced in the property
• android:layout_toRightOf indicates that the widget should be placed to the
right of the widget referenced in the property

33

The Relative Layout

3. Relative Layout – Referring to other widgets – cont.


• y _ g p indicates that the widget's
android:layout_alignTop g p should be aligned
top g with the
top of the widget referenced in the property

• android:layout_alignBottom indicates that the widget's bottom should be aligned


with the bottom of the widget referenced in the property

• android:layout_alignLeft indicates that the widget's left should be aligned with the
left of the widget referenced in the property

• android:layout_alignRight indicates that the widget's right should be aligned with


the right of the widget referenced in the property

• android:layout_alignBaseline indicates that the baselines of the two widgets


should be aligned

34
Lesson 4

The Relative Layout

3. Relative Layout – Referring to other widgets

When using relative positioning you need to:

1. Put identifiers ( android:id attributes ) on all elements that you will be


referring to.

2. XML elements are named using: @+id/... For instance an EditText box
could be called: android:id="@+id/txtUserName"

3. You must refer only to widgets that have been defined. For instance a new
control to be positioned below the previous EditText box could refer to it
using: android:layout_below="@+id/txtUserName"

35

The Relative Layout


3. Relative Layout – Example
<EditText
<?xml version="1.0" encoding="utf‐8"?> android:id="@+id/txtUserName"
<RelativeLayout android:layout_width="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content"
android:id="@+id/myRelativeLayout" android:layout_alignParentLeft="true"
android:layout width="fill
android:layout_width fill_parent
parent" android:layout below="@+id/lblUserName"
android:layout_below @ id/lblUserName
android:layout_height="fill_parent" android:padding="20dip" >
android:background="#ff000099" > </EditText>

<TextView <Button
android:id="@+id/lblUserName" android:id="@+id/btnGo"
android:layout_width="fill_parent" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentLeft="true" android:layout_alignRight="@+id/txtUserName"
android:layout_alignParentTop="true" android:layout_below="@+id/txtUserName"
android:background="#ffff0066" android:text="Go"
android:text="User Name" android:textStyle="bold" >
android:textColor="#ff000000" </Button>
android:textStyle="bold" >
</TextView>
/T tVi <Button
android:id="@+id/btnCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/txtUserName"
android:layout_toLeftOf="@+id/btnGo"
android:text="Cancel"
android:textStyle="bold" >
</Button>

</RelativeLayout>

36
Lesson 4

The Table Layout

4. Table Layout

1. Android's TableLayout uses a grid to position your widgets.


2. Cells in the grid are identifiable by rows and columns.
3. Columns might shrink or stretch to accommodate their contents.
4. The element TableRow is used to define a new row in which widgets can be
allocated.
5. The number of columns in a TableRow is determined by the total of side‐by‐
side widgets placed on the row.

38
Lesson 4

Basic XML Layouts ‐ Containers


4. Table Layout

Th number
The b off columns
l i a row is
in i determined
d t i d by
b Android.
A d id

So if you have three rows, one with two widgets, one with three
widgets, and one with four widgets, there will be at least four
columns.
0 1
0 1 2
0 1 2 3

39

Basic XML Layouts ‐ Containers


4. Table Layout
However, a single widget can take up more than one column by
However
including the android:layout_span property, indicating the number
of columns the widget spans (this is similar to the colspan attribute
one finds in table cells in HTML)
<TableRow>
<TextView android:text="URL:" />
<EditText
android:id="@+id/entry"
android:layout_span="3" />
</TableRow>

40
Lesson 4

Basic XML Layouts ‐ Containers


4. Table Layout

O di il widgets
Ordinarily, id t are putt into
i t the
th first
fi t available
il bl column
l off each
h row.

In the example below, the label (“URL”) would go in the first column
(column 0, as columns are counted starting from 0), and the TextField would go
into a spanned set of three columns (columns 1 through 3).

android:layout_span="3"

Label EditText EditText‐span EditText‐span


(URL)
Column 0 Column 1 Column 2 Column 3
Button Button
Cancel OK
android:layout_colum="2" 41

Basic XML Layouts ‐ Containers


<?xml version="1.0" encoding="utf‐8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myTableLayout"
4. Table Layout android:layout_width="fill_parent"
android:layout_height="fill_parent"
Example android:background="#ffffff00"
android:orientation="vertical" >
<TableRow>
<TextView android:text="URL:" />
<EditText
android:id="@+id/ediUrl"
android:layout_span="3" /> Strech up to column 3
</TableRow>
<View
android:layout_height="3dip"
android:background="#0000FF" />

<TableRow>
<Button
android:id="@+id/cancel"
android:id= @+id/cancel
android:layout_column="2" Skip columns: 0, 1
android:text="Cancel" />
<Button
android:id="@+id/ok"
android:text="OK" />
Note to the reader: </TableRow>
<View
Experiment changing android:layout_height="3dip"
layout_span to 1, 2, 3 android:background="#0000FF" />
</TableLayout>
42
Lesson 4

Basic XML Layouts ‐ Containers


4. Table Layout

By default,
B d f lt each h column
l will
ill be
b sized
i d according
di tot the
th ""natural"
t l" size
i
of the widest widget in that column.

If your content is narrower than the available space, you can use
the TableLayout property:

android:stretchColumns ==“…”

Its value should be a single column number (0‐based) or a comma‐


delimited list of column numbers. Those columns will be stretched
to take up any available space yet on the row.
43

Basic XML Layouts ‐ Containers


4. Table Layout
In our running example we stretch columns 2, 3, and 4 to fill the
restt off the
th row.
...
<TableLayout
android:id="@+id/myTableLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff0033cc"
android:orientation="vertical"
i i i i
android:stretchColumns ="2,3,4"
xmlns:android="http://schemas.android.com/apk/res/android"
>
...
TODO: try to stretch one column at the time 1, then 2, and so on.
44
Lesson 4

Basic XML Layouts ‐ Containers


5. ScrollView Layout

When we have
Wh h more data
d t than
th whath t can be
b shown
h on a single
i l
screen you may use the ScrollView control.

It provides a sliding or scrolling access to the data. This way the user
can only see part of your layout at one time, but the rest is available
via scrolling.

This is similar to browsing a large web page that forces the user to
scroll up the page to see the bottom part of the form.

45

Basic XML Layouts ‐ Containers


4. Example ScrollView Layout
<?xml version="1.0" encoding="utf‐8"?>

<ScrollView
S ll i
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myScrollView1" <TextView
android:layout_width="fill_parent" android:id="@+id/textView2"
android:layout_height="fill_parent" android:layout_width="fill_parent"
android:background="#ff009999" > android:layout_height="wrap_content"
android:text="Line2"
<LinearLayout android:textSize="150dip" />
android:id="@+id/myLinearLayoutVertical"
android:layout_width="fill_parent" <View
android:layout_height="fill_parent" android:layout_width="fill_parent"
android:orientation="vertical" > android:layout_height="6dip"
android:background="#ffccffcc"
android:background #ffccffcc />
<TextView
android:id="@+id/textView1" <TextView
android:layout_width="fill_parent" android:id="@+id/textView3"
android:layout_height="wrap_content" android:layout_width="fill_parent"
android:text="Line1" android:layout_height="wrap_content"
android:textSize="150dip" /> android:text="Line3"
<View android:textSize="150dip" />
android:layout_width="fill_parent" </LinearLayout>
android:layout_height="6dip"
android:background="#ffccffcc" /> </ScrollView>
46
Lesson 4

Basic XML Layouts ‐ Containers


5. Example ScrollView Layout

Scroller

Simple
TextView

47
Lesson 4

Basic XML Layouts ‐ Containers


6. Constraint Layout
For each Widget in ConstraintLayout to be
positioned correctly, it requires at least 2
constraints, one horizontal (X) and one
vertical (Y).

47
Lesson 4

Basic XML Layouts ‐ Containers


6. Constraint Layout

47
Lesson 4

Basic XML Layouts ‐ Containers


6. Constraint Layout

47
Lesson 4

Basic XML Layouts ‐ Containers


6. Constraint Layout

47
A Detailed List of Widgets
For a detailed list consult:

http://developer.android.com/reference/android/widget/package‐summary.html
AbsListView DigitalClock PopupWindow TableLayout.LayoutParams
AbsListView.LayoutParams EditText ProgressBar TableRow
AbsoluteLayout ExpandableListView RadioButton TableRow.LayoutParams
AbsoluteLayout.LayoutParams ExpandableListContextMenuInfo RadioGroup TabWidget
AbsSeekBar Filter RadioGroup.LayoutParams TextSwitcher
AbsSpinner Filter.FilterResults RatingBar TextView
AdapterView<T extends Adapter> FrameLayout RelativeLayout TextView.SavedState
AdapterContextMenuInfo FrameLayout.LayoutParams RelativeLayout.LayoutParams TimePicker
AlphabetIndexer Gallery RemoteViews Toast
AnalogClock Gallery.LayoutParams ResourceCursorAdapter ToggleButton
ArrayAdapter<T> GridView ResourceCursorTreeAdapter TwoLineListItem
AutoCompleteTextView HeaderViewListAdapter Scroller VideoView
BaseAdapter HorizontalScrollView ScrollView ViewAnimator
BaseExpandableListAdapter ImageButton SeekBar ViewFlipper
Button ImageSwitcher SimpleAdapter ViewSwitcher
CheckBox ImageView SimpleCursorAdapter ZoomButton
CheckedTextView LinearLayout SimpleCursorTreeAdapter ZoomControls
Chronometer LinearLayout.LayoutParams SimpleExpandableListAdapter
CompoundButton ListView SlidingDrawer
CursorAdapter ListView.FixedViewInfo Spinner
CursorTreeAdapter MediaController TabHost
DatePicker MultiAutoCompleteTextView TabHost.TabSpec
DialerFilter CommaTokenizer TableLayout

50
Lesson 4

Attaching Layouts to Java Code


PLUMBING. You must ‘connect’ the XML elements with equivalent objects
i your JJava activity.
in ti it Thi
This allows
ll you tto manipulate
i l t ththe UI with
ith code.
d
XLM Layout
<xml….
...
...
</xml>

JAVA code
public class ….
{
...
...
}
51

Attaching Layouts to Java Code


Assume the UI in res/layout/main.xml has been created. This layout could
b called
be ll d b
by an application
li ti using
i th
the statement
t t t

setContentView(R.layout.main);

Individual widgets, such as myButton could be accessed by the application


using the statement findViewByID(...) as in

Button btn = (Button) findViewById(R.id.myButton);


findViewById(R id myButton);

Where R is a class automatically generated to keep track of resources


available to the application. In particular R.id... is the collection of widgets
defined in the XML layout.

52
Lesson 4

Attaching Layouts to Java Code


Attaching Listeners to the Widgets

The button of our example could now be used, for instance a listener
for the click event could be written as:

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

private void updateTime() {


btn.setText(new Date().toString());
}

53

Basic Widgets: Labels


• A label is called in android a
TextView.
TextView

• TextViews are typically used for


output to display a caption.

• TextViews are not editable,


therefore they take no input.

54
Lesson 4

Basic Widgets: Labels


<?xml version="1.0" encoding="utf‐8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget32"
@ / g
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffffff00"
android:inputType="none"
android:text="@string/long_msg_1"
android:textSize="20sp" />

</LinearLayout>

Hint on Better Programming Style: Add to the res/values/stringg.xml the entry


<string name=“long_msg_1">Line1 of long message\nLine2 of long msg\n...\nlast line</string>
55

EditText Caution
WARNING
This text field does not specify an
InputType or a hint

is just a warning requesting your help to improve


the working of a TextView. Add the clause
android:hint=“…some hint here…” and/or
android:InputType=“…choice…” where choices are

56
Lesson 4

Basic Widgets / Attributes & Methods: TextView


http://developer.android.com/reference/android/widget/TextView.html
XML Attribute / Description
Equivalent Method
android:autoLink Controls whether links such as urls and email addresses are
setAutoLinkMask(int) automatically found and converted to clickable links.

android:autoText If set, specifies that this TextView has a textual input method and
setKeyListener(KeyListener) automatically corrects some common spelling errors.

android:bufferType Determines the minimum type that getText() will return.


setText(CharSequence,TextView.BufferType)

android:capitalize If set, specifies that this TextView has a textual input method and
setKeyListener(KeyListener) should automatically capitalize what the user types.

android:cursorVisible Makes the cursor visible (the default) or invisible.


setCursorVisible(boolean)

android:digits If set, specifies that this TextView has a numeric input method and
setKeyListener(KeyListener) that these specific characters are the ones that it will accept.

android:drawableBottom The drawable to be drawn below the text.


setCompoundDrawablesWithIntrinsicBounds( )

57

Basic Widgets / Attributes & Methods: TextView cont.


http://developer.android.com/reference/android/widget/TextView.html

XML Attribute / Description


Equivalent Method

android:drawableEnd The drawable to be drawn to the end of the text.


android:drawableLeft
d id d bl L ft Th drawable
The d bl tto be
b drawn
d t the
to th left
l ft off the
th text.
t t
setCompoundDrawablesWithIntrinsicBounds(int...)

android:drawablePadding The padding between the drawables and the text.


setCompoundDrawablePadding(int)
android:drawableRight The drawable to be drawn to the right of the text.
setCompoundDrawablesWithIntrinsicBounds(int...)

android:drawableStart The drawable to be drawn to the start of the text.


android:drawableTop The drawable to be drawn above the text.
setCompoundDrawablesWithIntrinsicBounds( )

android:editable If set, specifies that this TextView has an input method.

android:editorExtras Reference to an <input‐extras> XML resource containing


setInputExtras(int) additional data to supply to an input method, which is private to
the implementation of the input method.

58
Lesson 4

Basic Widgets / Attributes & Methods: TextView cont.


http://developer.android.com/reference/android/widget/TextView.html

XML Attribute / Description


Equivalent Method
android:ellipsize If set, causes words that are longer than the view is wide to be
setEllipsize(TextUtils.TruncateAt) ellipsized instead of broken in the middle.
android:ems
d id M k the
Makes h TextView
T Vi be b exactlyl this
hi many ems wide.
id
setEms(int)
android:fontFamily Font family (named by string) for the text.
setTypeface(Typeface)
android:freezesText If set, the text view will include its current complete text inside
setFreezesText(boolean) of its frozen icicle in addition to meta‐data such as the current
cursor position.
android:gravity Specifies how to align the text by the view's x‐ and/or y‐axis
setGravity(int) when the text is smaller than the view.
android:height Makes the TextView be exactly this many pixels tall.
setHeight(int)
android:hint p y when the text is empty.
Hint text to display py
setHint(int)

android:imeActionId Supply a value for EditorInfo.actionId used when an input


setImeActionLabel(CharSequence.) method is connected to the text view.

59

Basic Widgets / Attributes & Methods: TextView cont.


http://developer.android.com/reference/android/widget/TextView.html

XML Attribute / Description


Equivalent Method

android:imeActionLabel Supply a value for EditorInfo.actionLabel used when an input


setImeActionLabel(CharSequence )
setImeActionLabel(CharSequence.) method is connected to the text view.
view

android:imeOptions Additional features you can enable in an IME associated with


setImeOptions(int) an editor to improve the integration with your application.

android:includeFontPadding Leave enough room for ascenders and descenders instead of


setIncludeFontPadding(boolean) using the font ascent and descent strictly.

android:inputMethod If set, specifies that this TextView should use the specified
setKeyListener(KeyListener) input method (specified by fully‐qualified class name).

android:inputType The type of data being placed in a text field, used to help an
setRawInputType(int) input method decide how to let the user enter text.

android:lineSpacingExtra Extra spacing between lines of text.


setLineSpacing(float.)

android:lineSpacingMultiplier Extra spacing between lines of text, as a multiplier.


setLineSpacing(float.)

60
Lesson 4

Basic Widgets / Attributes & Methods: TextView cont.


http://developer.android.com/reference/android/widget/TextView.html

XML Attribute / Description


Equivalent Method
android:minEms Makes the TextView be at least this many ems wide.
setMinEms(int)
android:minHeight Makes the TextView be at least this many pixels tall.
setMinHeight(int)
android:minLines Makes the TextView be at least this many lines tall.
setMinLines(int)
android:minWidth Makes the TextView be at least this many pixels wide.
setMinWidth(int)
android:numeric If set, specifies that this TextView has a numeric input
setKeyListener(KeyListener) method.
android:password Whether the characters of the field are displayed as password
setTransformationMethod(TransformationMethod) dots instead of themselves.

android:phoneNumber If set, specifies that this TextView has a phone number input
setKeyListener(KeyListener) method.

61

Basic Widgets / Attributes & Methods: TextView cont.


http://developer.android.com/reference/android/widget/TextView.html

XML Attribute / Description


Equivalent Method
android:privateImeOptions An addition content type description to supply to the input
setPrivateImeOptions(String) method attached to the text view, which is private to the
i l
implementation
t ti off the
th input
i t method.
th d
android:scrollHorizontally Whether the text is allowed to be wider than the view (and
setHorizontallyScrolling(boolean) therefore can be scrolled horizontally).
android:selectAllOnFocus If the text is selectable, select it all when the view takes focus.
setSelectAllOnFocus(boolean)
android:shadowColor Place a shadow of the specified color behind the text.
setShadowLayer(float...)
android:shadowDx Horizontal offset of the shadow.
setShadowLayer(float...)
android:shadowDy Vertical offset of the shadow.
setShadowLayer(float...)
y
android:shadowRadius Radius of the shadow.
setShadowLayer(float...)
android:singleLine Constrains the text to a single horizontally scrolling line instead
setTransformationMethod(TransformationMethod) of letting it wrap onto multiple lines, and advances focus instead
of inserting a newline when you press the enter key.

62
Lesson 4

Basic Widgets / Attributes & Methods: TextView cont.


http://developer.android.com/reference/android/widget/TextView.html

XML Attribute / Description


Equivalent Method
android:privateImeOptions An addition content type description to supply to the input
setPrivateImeOptions(String) method attached to the text view, which is private to the
implementation
p of the input
p method.
android:scrollHorizontally Whether the text is allowed to be wider than the view (and
setHorizontallyScrolling(boolean) therefore can be scrolled horizontally).
android:selectAllOnFocus If the text is selectable, select it all when the view takes focus.
setSelectAllOnFocus(boolean)
android:shadowColor Place a shadow of the specified color behind the text.
setShadowLayer(float...)
android:shadowDx Horizontal offset of the shadow.
setShadowLayer(float...)
android:shadowDy Vertical offset of the shadow.
setShadowLayer(float...)
android:shadowRadius Radius of the shadow.
setShadowLayer(float )
setShadowLayer(float...)
android:singleLine Constrains the text to a single horizontally scrolling line instead
setTransformationMethod(TransformationMethod) of letting it wrap onto multiple lines, and advances focus
instead of inserting a newline when you press the enter key.

63

Basic Widgets / Attributes & Methods: TextView cont.


http://developer.android.com/reference/android/widget/TextView.html

XML Attribute / Description


Equivalent Method
android:text Text to display.
setText(CharSequence,TextView.BufferType)
android:textAllCaps Present the text in ALL CAPS.
setAllCaps(boolean)
android:textAppearance Base text color, typeface, size, and style.
android:textColor Text color.
setTextColor(int)
android:textColorHighlight Color of the text selection highlight.
setHighlightColor(int)
android:textColorHint Color of the hint text.
setHintTextColor(int)
android:textColorLink Text color for links.
setLinkTextColor(int)

android:textIsSelectable
d id t tI S l t bl I di t that
Indicates th t the
th content
t t off a non‐editable
dit bl text
t t can be
b
isTextSelectable() selected.

64
Lesson 4

Basic Widgets / Attributes & Methods: TextView cont.


http://developer.android.com/reference/android/widget/TextView.html
XML Attribute / Description
Equivalent Method
android:textScaleX Sets the horizontal scaling factor for the text.
setTextScaleX(float)
android:textSize Size of the text
text.
setTextSize(int.)
android:textStyle Style (bold, italic, bolditalic) for the text.
setTypeface(Typeface)
android:typeface Typeface (normal, sans, serif, monospace) for the text.
setTypeface(Typeface)
android:width Makes the TextView be exactly this many pixels wide.
setWidth(int)

65

Basic Widgets: Buttons


• A Button widget allows the simulation of a clicking action on a GUI.

• B tt is
Button i a subclass
b l off TextView.
T tVi Th f
Therefore formatting
f tti a button’s
b tt ’ face
f
is similar to the setting of a TextView.

<Button
android:id="@+id/button1"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="right“
android:layout_marginTop="20dp"
android:padding="5dp"
android:text="@string/button1_caption"
android:textColor="#ffff0000"
android:textSize="20sp"
android:textStyle="bold" />
66
Lesson 4

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 a reference to a drawable resource.

• ImageButton, is a subclass of ImageView. It adds the standard


Button behavior for responding to click events.

67

Basic Widgets: Images


<LinearLayout
. . .

<ImageButton
android:id="@+id/myImageBtn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" >
</ImageButton>

<ImageView This is a jpg,


android:id="@+id/myImageView1" gif, png,… file
android:layout_width="150dp"
d id l t idth "150d "
android:layout_height="120dp"
android:scaleType="fitXY"
android:src="@drawable/flower1" >
</ImageView>

</LinearLayout>
68
Lesson 4

Basic Widgets: Images


Icons are small images used to graphically represent your application and/or parts of it.
They may appear in different places of the device including:

• Home screen
• Launcher window.
• Options menu
• Action Bar
• Status bar
• Multi‐tab interface.
• Pop‐up dialog boxes
• List view

Detailed information at:


http://developer.android.com/guide/practices/ui_guidelines/icon_design.html

HINT
Several websites allow you to convert your pictures into arbitrary image files under a
variety of formats & sizes (.png, .jpg, .gif, etc). For instance try;
http://www.prodraw.net/favicon/index.php
http://converticon.com/
69

Basic Widgets: EditText


• The EditText (or textBox)
widget
d is an extension off
TextView that allows updates.

• The control configures itself to


be editable.

• Important Java methods are:

txtBox.setText(“someValue”)
and
txtBox.getText().toString()

70
Lesson 4

Basic Widgets: EditText


In addition to the standard TextView’s properties, EditText
h many other
has th ((now)) deprecated
d t d features
f t such
h 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 field’s visibility
• android:numeric, (integer, decimal, signed) controls numeric format
• android:phonenumber, (true/false) Formatting phone numbers

Instead use the newer clause

android:InputType=“…choices…”
where choices include

71

Basic Widgets: EditViews


Example

...

<EditText
android:id="@+id/txtUserName"
android:layout_width="fill_parent" Enter “teh” It will
android:layout_height="wrap_content" be changed to: “the”

android:inputType="textCapWords|textAutoCorrect"

android:hint="Enter your First and Last Name"


android:textSize="18sp" >
Each word is
... capitalized

Suggestion (grey out)

72
Lesson 4

Basic Widgets: Example 1


In this little example we will create and use a simple login
screen holding a label( TexView), a textBox (EditText), and a
B tt
Button.

Setting
Hint Capitals & text
spelling

A brief
message box

73

Basic Widgets: Example 1


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" <Button
android:layout_width="fill_parent" android:id="@+id/button1"
android:layout_height="fill_parent" android:layout_width="82dp"
android:background="#ff6495ed" android:layout_height="wrap_content"
android:orientation="vertical"
d id i t ti " ti l" > android:text="Login" />

<TextView </LinearLayout>
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff00"
android:text=" ACME Corporation‐Login " />

<EditText
android:id="@+id/txtUserName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"

android:inputType="textCapWords|textAutoCorrect"

android:hint="Enter your First and Last name"


android:textSize="18sp" >

<requestFocus />
</EditText>

74
Lesson 4

Basic Widgets: Example 1


Android’s Application (1 of 2)
package cis493.gui;
import ...
// "LOGIN" - a gentle
tl iintroduction
t d ti t
to UI controls
t l

public class AndDemo extends Activity {


TextView labelUserName;
EditText txtUserName;
Button btnBegin;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

//binding the UI's controls defined in "main.xml" to Java code


labelUserName = (TextView) findViewById(R.id.textView1);
txtUserName = (EditText) findViewById(R.id.txtUserName);
btnBegin = (Button) findViewById(R.id.button1);

75

Basic Widgets: Example 1


Android’s Application (2 of 2)
//LISTENER: wiring
g the button widget
g to events-&-code
btnBegin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String userName = txtUserName.getText().toString();
if (userName.compareTo("Maria Macarena")==0){
labelUserName.setText("OK, please wait...");
Toast.makeText(getApplicationContext(),
"Bienvenido " + userName,
Toast.LENGTH_SHORT).show();
}
Toast makeText(getApplicationContext()
Toast.makeText(getApplicationContext(),
"Bienvenido " + userName,
Toast.LENGTH_SHORT).show();
}

});// onClick

}//onCreate

}//class 76
Lesson 4

Your turn!
I l
Implementt any/all
/ ll off th
the ffollowing
ll i projects
j t
Using simple text boxes (EditText, TextView)
and buttons:

1. Currency calculator
2. Tip Calculator
3. Simple Flashlight

77

Basic Widgets: Example 2


Note: Another way of defining a Listener for multiple button widgets
public class SimpleUI extends Activity implements OnClickListener {
Button btnBegin;
Button btnExit;
b i
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

btnBegin = (Button) findViewById(R.id.btnBegin);


btnExit = (Button) findViewById(R.id.btnExit);

btnBegin.setOnClickListener(this);
btnExit.setOnClickListener(this);
}//onCreate

@Override
public void onClick(View v) {
if (v.getId()==btnBegin.getId() ){
Toast.makeText(getApplicationContext(), "1-Begin", 1).show();
}
if (v.getId()==btnExit.getId() ){
Toast.makeText(getApplicationContext(), "2-Exit", 1).show();
}
}//onClick
}//class
78
Lesson 4

Basic Widgets: CheckBox


A checkbox is a specific type of two‐states
b tt that
button th t can be
b either
ith checked
h k d or
unchecked.

A example usage of a checkbox inside your


activity would be the following:

79

Example 3: CheckBox
Complete code for the checkBox demo (1 of 3)
Layout: main.xml
<CheckBox
<?xml version="1.0" encoding="utf-8"?> android:id="@+id/chkCream"
<LinearLayout android:layout_width="wrap_content"
android:id="@+id/linearLayout" android:layout_height="wrap_content"
android:layout_width="fill_parent" android:text="Cream"
android:layout_height="fill_parent" android:textStyle="bold"
android:background="#ff666666" >
android:orientation="vertical" </CheckBox>
xmlns:android="http://schemas.android.com/a <CheckBox
pk/res/android" android:id="@+id/chkSugar"
> android:layout_width="wrap_content"
android:layout_height="wrap_content"
<TextView android:text="Sugar"
android:id="@+id/labelCoffee"
@ / android:textStyle="bold"
y
android:layout_width="fill_parent" >
android:layout_height="wrap_content" </CheckBox>
android:background="#ff993300" <Button
android:text="What else in you Coffee ?" android:id="@+id/btnPay"
android:textStyle="bold" android:layout_width="153px"
> android:layout_height="wrap_content"
</TextView> android:text="Pay"
android:textStyle="bold"
>
</Button>
</LinearLayout>
80
Lesson 4

Example 2: CheckBox
Complete code for the checkBox demo (2 of 3)
public class MainActivity Activity {
CheckBox chkCream;
CheckBox chkSugar;
Button btnPay;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//binding XMl controls with Java code
chkCream = (CheckBox)findViewById(R.id.chkCream);
chkSugar = (CheckBox)findViewById(R.id.chkSugar);
btnPay = (Button) findViewById(R.id.btnPay);

81

Example 2: CheckBox
Complete code for the checkBox demo ( 3 of 3 )
//LISTENER: wiring button-events-&-code
btnPay setOnClickListener(new OnClickListener() {
btnPay.setOnClickListener(new

@Override
public void onClick(View v) {
String msg = "Coffee ";
if (chkCream.isChecked()) {
msg += " & cream ";
}
if (chkSugar.isChecked()){
msg += " & Sugar";
}
T
Toast.makeText(getApplicationContext(),
t k T t( tA li ti C t t()
msg, Toast.LENGTH_SHORT).show();
//go now and compute cost...

}//onClick

});
}//onCreate
}//class
82
Lesson 4

Basic Widgets: RadioButtons


• A radio button is a two‐states button that can be either checked or
unchecked.
h k d
• 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.

83

Basic Widgets: RadioButtons


Example
We extend the previous example by adding a RadioGroup and three
RadioButtons. Only new XML and Java code is shown:
<TextView
< e t e
android:id="@+id/textView1" <RadioGroup
android:layout_width="fill_parent" android:id="@+id/radioGroupCoffeeType"
android:layout_height="wrap_content" android:layout_width="match_parent"
android:background="#ff993300" android:layout_height="wrap_content" >
android:text="What kind of Coffee?"
android:textColor="#ffffff" <RadioButton
android:textStyle="bold" /> android:id="@+id/radDecaf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Decaf" />

<RadioButton
android:id="@+id/radExpresso"
android:layout_width= wrap_content
android:layout width "wrap content"
android:layout_height="wrap_content"
android:text="Expresso" />

<RadioButton
android:id="@+id/radColombian"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Colombian" />

</RadioGroup> 84
Lesson 4

Basic Widgets: RadioButtons


public class MainActivity extends Activity {
CheckBox chkCream;
CheckBox chkSugar;
Button btnPay;

RadioGroup radCoffeeType;
RadioButton radDecaf;
RadioButton radExpresso;
RadioButton radColombian;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
chkCream = (CheckBox) findViewById(R.id.chkCream);
chkSugar
hk = (CheckBox)
( h k ) findViewById(R.id.chkSugar);
fi d i d( id hk )
btnPay = (Button) findViewById(R.id.btnPay);
radCoffeeType = (RadioGroup) findViewById(R.id.radioGroupCoffeeType);
radDecaf = (RadioButton) findViewById(R.id.radDecaf);
radExpresso = (RadioButton) findViewById(R.id.radExpresso);
radColombian = (RadioButton) findViewById(R.id.radColombian);

85

Basic Widgets: RadioButtons


// LISTENER: wiring button‐events‐&‐code
btnPay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String msg = "Coffee ";
if (chkCream.isChecked())
msg += " & cream "
";
if (chkSugar.isChecked())
msg += " & Sugar";

// get radio buttons ID number


int radioId = radCoffeeType.getCheckedRadioButtonId();

// compare selected's Id with individual RadioButtons ID


if (radColombian.getId() == radioId)
msg = "Colombian " + msg;
// similarly you may use .isChecked() on each RadioButton
if (radExpresso.isChecked())
msg = "Expresso
Expresso " + msg;
// similarly you may use .isChecked() on each RadioButton
if (radDecaf.isChecked())
msg = "Decaf " + msg;

Toast.makeText(getApplicationContext(), msg, 1).show();


// go now and compute cost...
}// onClick
});
}// onCreate

}// class 86
Lesson 4

Basic Widgets: RadioButtons


Example

This UI uses
RadioButtons RadioGroup
and
CheckBoxes
to define choices

Summary of choices

87

UI – Other Features

XML Controls the focus sequence:


android:visibility
qndroid:background
<requestFocus />

Java methods
myButton.requestFocus()
myTextBox.isFocused()
T tB i F d()
myWidget.setEnabled()
myWidget.isEnabled()

88
Lesson 4

UI ‐ User Interfaces

Questions ?

89

UI ‐ User Interfaces
Resource: DroidDraw www.droidDraw.org

90
Lesson 4

Android Asset Studio – Beta (Accessed: Sep 11, 2012)


AAS Link: http://code.google.com/p/android‐ui‐utils/
Icon Gen http://android‐ui‐utils.googlecode.com/hg/asset‐studio/dist/index.html
Pencil 1.2 http://pencil.evolus.vn/en‐US/Home.aspx
Video: http://www.youtube.com/watch?v=EaT7sYr_f0k&feature=player_embedded

WARNING Th
WARNING: These utilities
ili i are currently
l iin b
beta.

Utilities that help in the design and development of Android application user interfaces. This library currently
consists of three individual tools for designers and developers:
1. UI Prototyping Stencils
A set of stencils for the Pencil GUI prototyping tool, which is available as an add‐on for Firefox or as a
standalone download.
2. Android Asset Studio
Try out the beta version: Android Asset Studio (shortlink: http://j.mp/androidassetstudio)
A web‐based set of tools for generating graphics and other assets that would eventually be in an Android
application's res/ directory.
Currently available asset generators area available for:
Launcher icons
Menu icons
Tab icons
Notification icons
Support for creation of XML resources and nine‐patches is planned for a future release.
3. Android Icon Templates
A set of Photoshop icon templates that follow the icon design guidelines, complementing the
official Android Icon Templates Pack.
91

Questions ‐ Measuring Graphic Elements


Q. What is dpi ?
Stands for dots per inch. You can compute it using the following formula:

dpi  widthPixel s 2  heightPixe ls 2 / diagonalIn ches


dpi = sqrt (width_pixels^2 + height_pixels^2) / diagonal_inches

G1 (base device 320x480) 155.92 dpi (3.7 in diagonally)


Nexus (480x800) 252.15 dpi

Q. What is the difference between px, dip, dp and sp units in Android?


dp (also known as dip)
Density‐independent Pixels – is an abstract unit based on the physical density of the screen. These
units are relative to a 160 dpi screen, so one dp is one pixel (px) on a 160 dpi screen.
Use it for measuring anything but fonts – DO NOT USE px, px in.
in mm

sp
Scale‐independent Pixels – similar to the relative density dp unit, but used for font size preference.

92
Lesson 4

Questions ‐ Measuring Graphic Elements

Q. How Android deals with screen resolutions?

Illustration of how the Android platform maps actual screen densities and sizes to generalized
density and size configurations.

93

Questions ‐ Measuring Graphic Elements


Q. What do I gain by using screen densities?
More homogeneous results as shown below
Examples of density
independence on WVGA high
density (left),
(left) HVGA medium
density (center), and QVGA
low density (right).

Q. How to set different density/size screens in my application?


The following manifest fragments declares support for small, normal, large, and xlarge screens in
any density.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<supports‐screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:xlargeScreens="true" />
...
</manifest> 94
Lesson 4

Questions ‐ Measuring Graphic Elements


Q. Give me an example on how to use dip units.
Assume you design your interface for a G1 phone having 320x480 pixels (Abstracted
LCD density is 160 – See your AVD entry the actual pixeling is a: 2*160 x 3*160)

Assume you want a 120dp button to be placed in the middle of the screen.
O portrait
On i mode
d you could
ld allocate
ll the
h 320 horizontal
h i l pixels
i l as [ 100
00 + 120
20 + 100
00 ].
]
On Landscape mode you could allocate 480 pixels as [ 180 + 120 + 180 ].

The XML would be

<Button
180 120 180
android:id="@+id/button1"
android:layout_height="wrap_content"
android:layout_width="120dp" 480
android:layout_gravity="center"
android:text="@+id/go_caption" />

Instead of using pixels (px) you should use dip/dp. If the application is deployed on a higher
resolution screen (more pixels in 1 dip) the button is still mapped to the middle of the
screen.

95

Hierarchy Viewer Tools


Can be added to the Eclipse IDE as a
Perspective option.
Allows exploration/magnification of a
displayed UI

9696

You might also like