Android Development
Android Development
Victor Matos
Cleveland State University
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, and (3) input logic.
• 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.
22
The Model-View-Control (MVC)
Pattern
Getting ready to create MVC conforming solutions
The Android developer should be aware of …
objects.html
4
Android & the MVC
The ViewPattern
- User Interfaces (Uis)
Android graphical interfaces are usually implemented as XML files (although
they could also be dynamically created from code).
Reference: http://developer.android.com/guide/topics/ui/layout-
objects.html 6
UI Design
Patterns 5
objects.html
7
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.
objects.html
8
Graphical ↔ XML
UI 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_centerHorizontal="true"
android:layout_marginTop="24dp"
android:text=" Go " />
</RelativeLayout>
objects.html
9
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.
</LinearLayout>
objects.html
8
10
Using Views
Dealing with widgets & layouts typically involves the following
operations
Reference: http://developer.android.com/guide/topics/ui/layout-
objects.html 11
Using Views
9
objects.html
12
A brief sample of UI
components
Layouts
objects.html
10
A brief sample of UI
components
Linear Layout
A LinearLayout places its
Relative Layout
A RelativeLayout is a ViewGroup
Table Layout
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.
objects.html
11
A brief sample of UI
components
Widgets
GalleryView
TabWidget
Spinner
objects.html
12
A brief sample of UI
components
TimePicker
AnalogClock
Form Controls
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.
objects.html
13
A brief sample of UI
components WebView
MapView
AutoCompleteTextView ListView
It is a version of the A ListView is a View that
EditText widget that will shows items in a vertically
provide scrolling list. The items are
auto-complete suggestions acquired from a ListAdapter.
as the user types. The
suggestions are extracted
from a collection of strings.
objects.html
14
XML Layouts in
Android considersEclipse
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
XML Layouts in
Eclipse of an XML file can be seen in Eclipse by
A reasonable UI representation
clicking the [Graphical Layout] tab of the res/layout/main.xml resource
14
XML Layouts in
Switch between
UI and XML view
Control properties
Eclipse
15
Tools for Android UI/XML
Design
ASIDE - CREATING ANDROID UI & APPS
You could create Layout XML files using UI tools such as:
17
Common Layouts
We will discuss the following common and useful layouts:
Frame, Linear, Relative, Table, and Absolute.
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.
• All its children elements are aligned to the top left corner
of the screen.;
17
The
LinearLayout
1. Linear Layout
19
The
LinearLayout
1. 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"
19
20
The LinearLayout -
Orientation
1.1 Linear Layout: Orientation <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/myLinearLayout"
21
The LinearLayout -
Orientation
horizontal android:layout_width="fill_parent"
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"
v android:layout_width="wrap_content"
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 android:id="@+id/ediName"
a android:layout_width="wrap_content"
l 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>
22
The LinearLayout – Fill
Model
1.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
involved (as is the case of the empty text box shown below).
21
The LinearLayout – Fill
Model
natural sizes
empty screen space
22
The LinearLayout – Fill
Model
1.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
23
The LinearLayout – Fill
Model
The LinearLayout – Fill
Model <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/myLinearLayout"
android:layout_width="fill_parent"
1.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"
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_parent"
android:layout_height="wrap_content"
android:textSize="18sp" />
<Button
android:id="@+id/btnGo"
android:layout_width="125dip"
Specific size: 125dip
android:layout_height="wrap_content"
android:text="Go"
android:textStyle="bold" />
</LinearLayout>
Medium resolution is: 320 x 480 dpi. 23
The LinearLayout –
Weight
1.2 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
the extra space given to that widget.
Example
The XML specification for the window is
very similar to the previous example.
The LinearLayout –
Weight
The TextView and Button controls
have
the additional property Takes: 2 /(1+1+2)
of the screen space
android:layout_weight="1"
Default value is 0
24
The LinearLayout –
Gravity
The LinearLayout –
Gravity
1.3 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
1.3 CAUTION: gravity vs. layout_gravity
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
The LinearLayout –
Padding
1.4 Linear Layout: Padding
• The padding specifies how much extra space 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.
The LinearLayout –
Padding
1.3 Linear Layout: Padding and Marging
The LinearLayout –
Padding
1.3 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>
...
The LinearLayout –
Margin
1.4 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
<EditText android:id="@+id/ediName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_margin="6dip"
>
</EditText>
...
30
The Relative
Layout
2. Relative Layout
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
The Relative
Layout 31
The Relative
Layout
2. 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 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
32
The Relative
Layout
2. Relative Layout – Referring to other widgets
33
The Relative
Layout
2. Relative Layout – Referring to other widgets – cont.
• android:layout_alignTop indicates that the widget's top should be aligned with
the top 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
34
The Relative
Layout
2. Relative Layout – Referring to other widgets
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
2. Relative LayoutLayout
– Example
The Relative
Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
<EditText android:id="@+id/txtUserName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_alignParentLef ="true
android:id="@+id/myRelativeLayout" t
android:layout_belo "
="@+id/lblUserNam e"
android:layout_width="fill_parent" android:padding="20dip" >
android:layout_height="fill_parent" </EditText>
android:background="#ff000099" >
<Button android:id="@+id/btnGo"
<TextView android:id="@+id/lblUserName" android:layout_width="wrap_content"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLef = "true" android:layout_alignRigh =e "
t
android:layout_alignParentTo ="true t
android:layout_belo =e "
android:background="#ffff0066" android:text="Go"
android:text="User Name" android:textStyle="bold" >
android:textColor="#ff000000" </Button>
android:textStyle="bold" >
</TextView> <Button android:id="@+id/btnCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
= "
android:layout_belo e =
w
android:text="Cancel"
android:layout_toLeftO o "
android:textStyle="bold" >
</Button>
</RelativeLayout>
36
36
2. Relative Layout (as of Sept 2012)
Using Eclipse ADT
Layout Editor
for designing a
RelativeLayout.
37
The Table
Layout
3. Table Layout
38
Basic XML Layouts -
Containers
3. Table Layout
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
3. Table Layout
However, a single widget can take up more than one column by
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>
Basic XML Layouts -
Containers
3. Table Layout
Ordinarily, widgets are put into the first available column of each 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"
42
Basic XML Layouts -<?xml version="1.0" encoding="utf-8"?>
Containers
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myTableLayout"
3. 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:layout_column="2" Skip columns: 0, 1
android:text="Cancel" />
<Button
android:id="@+id/ok"
android:text="OK" />
</TableRow>
Note to the reader:
<View android:layout_height="3dip"
Experiment changing android:background="#0000FF" />
layout_span to 1, 2, 3 </TableLayout>
43
3. Table Layout
If your content is narrower than the available space, you can use
the TableLayout property:
android:stretchColumns =“…”
...
<TableLayout
android:id="@+id/myTableLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff0033cc"
android:orientation="vertical"
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.
Basic XML Layouts -
Containers
4. ScrollView Layout
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.
Basic XML Layouts -
Containers
4. Example ScrollView Layout
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
Basic XML Layouts -
xmlns:android="http://schemas.android.com/apk/res/android"
Containers
android:id="@+id/myScrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
<TextView android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff009999" > android:text="Line2"
android:textSize="150dip" />
<LinearLayout
android:id="@+id/myLinearLayoutVertical" <View
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_height="6dip"
android:orientation="vertical" > android:background="#ffccffcc" />
4646
Basic XML Layouts -
Containers
4. Example ScrollView Layout
Basic XML Layouts - Scroller
Containers
Simple
TextView
47
Basic XML Layouts -
Containers
5. Miscellaneous.
Absolute Layout
48
Basic XML Layouts -
Containers
5. Miscellaneous Absolute Layout (cont.)
Basic XML Layouts -
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
Containers
android:id="@+id/myLinearLayout"
android:layout_width="fill_parent"
</TextView>
<EditText android:id="@+id/etName"
android:layout_height="fill_parent" android:layout_width="fill_parent"
android:background="#ff0033cc" android:layout_height="wrap_content"
android:padding="4dip" android:textSize="18sp"
xmlns:android="http://schemas.android.com android:layout_x="0dip"
/apk/res/android" android:layout_y="38dip"
> >
</EditText>
<TextView
android:id="@+id/tvUserName" <Button
android:layout_width="fill_parent" android:layout_width="120dip"
android:layout_height="wrap_content" android:text="Go"
android:background="#ffff0066" android:layout_height="wrap_content"
android:text="User Name" android:textStyle="bold"
android:textSize="16sp" android:id="@+id/btnGo"
android:textStyle="bold" android:layout_x="100dip"
android:textColor="#ff000000" android:layout_y="170dip" />
android:layout_x="0dip" </AbsoluteLayout>
android:layout_y="10dip"
>
4949
A Detailed List of Widgets
For a detailed list consult:
http://developer.android.com/reference/android/widget/package-summary.html
AbsListView.LayoutParams EditText ExpandableListView ProgressBar TableRow
AbsoluteLayout ExpandableListContextMenuInfo RadioButton TableRow.LayoutParams
AbsoluteLayout.LayoutParams Filter RadioGroup TabWidget
AbsSeekBar Filter.FilterResults RadioGroup.LayoutParams TextSwitcher
AbsSpinner FrameLayout RatingBar TextView
AdapterView<T extends Adapter> FrameLayout.LayoutParams RelativeLayout TextView.SavedState
AdapterContextMenuInfo Gallery RelativeLayout.LayoutParams TimePicker
AlphabetIndexer Gallery.LayoutParams RemoteViews Toast
AnalogClock GridView ResourceCursorAdapter ToggleButton
ArrayAdapter<T> HeaderViewListAdapter ResourceCursorTreeAdapter TwoLineListItem
AutoCompleteTextView HorizontalScrollView Scroller VideoView
BaseAdapter ImageButton ScrollView ViewAnimator
BaseExpandableListAdapter ImageSwitcher SeekBar ViewFlipper
Button ImageView SimpleAdapter ViewSwitcher
CheckBox LinearLayout SimpleCursorAdapter ZoomButton
CheckedTextView LinearLayout.LayoutParams SimpleCursorTreeAdapter ZoomControls
Chronometer ListView SimpleExpandableListAdapter
AbsListView DigitalClock PopupWindow TableLayout.LayoutParams
CompoundButton ListView.FixedViewInfo SlidingDrawer
CursorAdapter MediaController Spinner
CursorTreeAdapter MultiAutoCompleteTextView TabHost
DatePicker TabHost.TabSpec
50
JAVA code
public class ….
{
...
...
}
Attaching Layouts to Java
Code
Assume the UI in res/layout/main.xml has been created. This layout could
be called by an application using the statement
setContentView(R.layout.main);
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();
}
});
<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>
57
Basic Widgets / Attributes & Methods: TextView
http://developer.android.com/reference/android/widget/TextView.html
57
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:capitalize If set, specifies that this TextView has a textual input method and
setKeyListener(KeyListener) should automatically capitalize what the user types.
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.
58
Basic Widgets / Attributes & Methods: TextView
cont.
XML Attribute / Description
Basic Widgets
Equivalent Method / Attributes & Methods: TextView
cont.
android:drawableEnd The drawable to be drawn to the end of the text.
android:drawableLeft The drawable to be drawn to the left of the text.
setCompoundDrawablesWithIntrinsicBounds(int...)
58
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.
) Makes the TextView be exactly this many ems wide.
android:ems
setEms(int) Font family (named by string) for the text.
android:fontFamily
setTypeface(Typeface) If set, the text view will include its current complete text inside
android:freezesText of its frozen icicle in addition to meta-data such as the current
setFreezesText(boolean) cursor position.
Specifies how to align the text by the view's x- and/or y-axis
android:gravity when the text is smaller than the view.
setGravity(int) Makes the TextView be exactly this many pixels tall.
android:height
setHeight(int) Hint text to display when the text is empty.
android:hint
setHint(int)
59
XML Attribute / Description
Equivalent Method
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.
60
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
setMinWidth(int)
android:numeric wide.
setKeyListener(KeyListener)
android:password If set, specifies that this TextView has a numeric input
setTransformationMethod(TransformationMethod method.
)
Whether the characters of the field are displayed as password
dots instead of themselves.
android:phoneNumber If set, specifies that this TextView has a phone number input
setKeyListener(KeyListener) method.
61
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 of the input 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...)
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
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 of the input 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...)
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
XML Attribute / Description
Equivalent Method
android:text Text to display.
setText(CharSequence,TextView.BufferType
) Present the text in ALL CAPS.
android:textAllCaps
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)
64
XML Attribute / Description
Equivalent Method
android:textScaleX Sets the horizontal scaling factor for the text.
setTextScaleX(float)
android:textSize Size of the text.
setTextSize(int.)
android:textStyle Style (bold, italic, bolditalic) for the text.
setTypeface(Typeface)
android:typeface Typeface (normal, sans, serif, monospace) for the
setTypeface(Typeface)
android:width text. Makes the TextView be exactly this many pixels
setWidth(int)
wide.
65
Basic Widgets: Buttons
• A Button widget allows the simulation of a clicking action on a GUI.
<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
Basic Widgets:
• ImageViewImages
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.
67
Basic Widgets:
<LinearLayout
. . .
Images
<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,
Basic Widgets:
android:id="@+id/myImageView1"
android:layout_width="150dp"
gif, png,… file
Images
android:layout_height="120dp"
android:scaleType="fitXY"
android:src="@drawable/flower1" >
</ImageView>
</LinearLayout>
68
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
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/
Basic Widgets:
EditText
• The EditText (or textBox)
widget is an extension of
TextView that allows updates.
txtBox.setText(“someValue”
) and
txtBox.getText().toString()
Basic Widgets:
EditText
In addition to the standard TextView’s properties, EditText
has many other (now) deprecated 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 field’s visibility
• android:numeric, (integer, decimal, signed) controls numeric format
• android:phonenumber, (true/false) Formatting phone numbers
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"
72
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
Button.
Setting
text
A brief
message box
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" <Button android:id="@+id/button1"
android:layout_width="fill_parent" android:layout_width="82dp"
android:layout_height="fill_parent" android:layout_height="wrap_content"
android:background="#ff6495ed" android:text="Login" />
android:orientation="vertical" >
</LinearLayout>
<TextView 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"
<requestFocus />
</EditText>
Android’s Application (1 of 2)
package cis493.gui;
import ...
////////////////////////////////////////////////////////////////////////
// "LOGIN" - a gentle introduction to UI controls
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
});// onClick
}//onCreate
}//class
7676
Your turn!
Implement any/all of the following projects
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;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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
Basic Widgets: CheckBox
A checkbox is a specific type of two-states
button that can be either checked or
unchecked.
79
Example 3:
CheckBox
Layout: main.xml
<CheckBox android:id="@+id/chkCream"
<?xml version="1.0" encoding="utf-8"?> android:layout_width="wrap_content"
<LinearLayout android:layout_height="wrap_content"
android:id="@+id/linearLayout" android:text="Cream"
android:layout_width="fill_parent" android:textStyle="bold"
android:layout_height="fill_parent" >
android:background="#ff666666" </CheckBox>
android:orientation="vertical" <CheckBox
xmlns:android="http://schemas.android.com/a android:id="@+id/chkSugar"
pk/res/android" android:layout_width="wrap_content"
> android:layout_height="wrap_content"
android:text="Sugar"
<TextView android:id="@+id/labelCoffee" android:textStyle="bold"
android:layout_width="fill_parent" >
android:layout_height="wrap_content" </CheckBox>
android:background="#ff993300" <Button android:id="@+id/btnPay"
android:text="What else in you Coffee ?" android:layout_width="153px"
android:textStyle="bold" android:layout_height="wrap_content"
> android:text="Pay"
</TextView> android:textStyle="bold"
>
</Button>
1
Example 3:
CheckBox</LinearLayout>
2
Example 2:
CheckBox
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
//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";
}
Toast.makeText(getApplicationContext(),
msg, Toast.LENGTH_SHORT).show();
//go now and compute cost...
}//onClick
});
}//onCreate
}//class
82
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.
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
Basic Widgets: RadioButtons
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
<RadioGroup
android:id="@+id/radioGroupCoffeeType"
android:layout_width="match_parent"
android:background="#ff993300" android:layout_height="wrap_content" >
android:text="What kind of Coffee?"
android:textColor="#ffffff" <RadioButton android:id="@+id/radDecaf"
android:textStyle="bold" /> 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_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
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 = (CheckBox) findViewById(R.id.chkSugar);
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";
}// class
8686
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()
myWidget.setEnabled()
myWidget.isEnabled()
UI - User
Interfaces
Questions ?
UI - User Interfaces
Resource: DroidDraw www.droidDraw.org
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
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:
92
dpi widthPixel s 2 heightPixe / diagonalInches
2
ls
G1 (base device 320x480) 155.92 dpi (3.7 in diagonally)
Nexus (480x800) 252.15 dpi
sp
Scale-independent Pixels – similar to the relative density dp unit, but used for font size preference.
93
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.
Questions - Measuring Graphic
Elements
More homogeneous results as shown below
Examples of density
independence on WVGA high
density (left), HVGA medium
density (center), and QVGA
low density (right).
Questions - Measuring Graphic
Elements
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
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.
On portrait mode you could allocate the 320 horizontal pixels as [ 100 + 120 + 100 ].
On Landscape mode you could allocate 480 pixels as [ 180 + 120 + 180 ].
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
969696