Week 4
Week 4
Lesson 4
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.
• 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
UI Design Patterns
For a detailed discussion on Android UI Design Patterns see video:
http://www.youtube.com/watch?v=M1ZBjlCRfz0&feature=player_embedded
6
Lesson 4
<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>
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>
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.
3. Set focus: To set focus on a specific view, you call the method
requestFocus() or use XML tag <requestFocus />
GalleryView
TabWidget
Spinner
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
You could create Layout XML files using UI tools such as:
• Wondershare Mockitt
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.
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"
19
<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
natural sizes
empty screen space
21
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
22
Lesson 4
<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
Example
The XML specification for the window is
very similar to the previous example.
Default value is 0
24
Lesson 4
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
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 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
28
Lesson 4
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
<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
3. 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
31
• 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
Lesson 4
33
• android:layout_alignLeft indicates that the widget's left should be aligned with the
left of the widget referenced in the property
34
Lesson 4
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
<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
4. Table Layout
38
Lesson 4
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
40
Lesson 4
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"
<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
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 ==“…”
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
<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
Scroller
Simple
TextView
47
Lesson 4
47
Lesson 4
47
Lesson 4
47
Lesson 4
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
JAVA code
public class ….
{
...
...
}
51
setContentView(R.layout.main);
52
Lesson 4
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();
}
});
53
54
Lesson 4
<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>
EditText Caution
WARNING
This text field does not specify an
InputType or a hint
56
Lesson 4
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.
57
58
Lesson 4
59
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
Lesson 4
android:phoneNumber If set, specifies that this TextView has a phone number input
setKeyListener(KeyListener) method.
61
62
Lesson 4
63
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
65
• 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
67
<ImageButton
android:id="@+id/myImageBtn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" >
</ImageButton>
</LinearLayout>
68
Lesson 4
• 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/
69
txtBox.setText(“someValue”)
and
txtBox.getText().toString()
70
Lesson 4
android:InputType=“…choices…”
where choices include
71
...
<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
Lesson 4
Setting
Hint Capitals & text
spelling
A brief
message box
73
<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"
<requestFocus />
</EditText>
74
Lesson 4
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
75
});// 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
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
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
• 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
<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
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
}// class 86
Lesson 4
This UI uses
RadioButtons RadioGroup
and
CheckBoxes
to define choices
Summary of choices
87
UI – Other Features
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
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
sp
Scale‐independent Pixels – similar to the relative density dp unit, but used for font size preference.
92
Lesson 4
Illustration of how the Android platform maps actual screen densities and sizes to generalized
density and size configurations.
93
<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
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 ].
<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
9696