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

Android Chapter04 User Interfaces

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

Android Chapter04 User Interfaces

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

Android - Graphical User Interfaces

The Model-View-Control Pattern (MVC)


Lesson 4 The Model-View-Controller (MVC) is an
important software design pattern first
introduced with the Xerox-Smalltalk80 system
whose main goal is to separate the (1) user

Graphical User Interfaces interface, (2) business, and (3) input logic.
How is this pattern seen by the Android developer?

• Model. Consists of the Java code and API objects used to represent the
Victor Matos business problem and manage the behavior and data of the application.
Cleveland State University • 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, touch-screen, GPS
chip, proximity sensor, accelerometer, etc, and tells the Model and/or the
View (usually through callbacks and registered listeners) to change as
Portions of this page are reproduced from work created and shared by Google and used according to terms appropriate.
described in the Creative Commons 3.0 Attribution License.

4-2

Android - Graphical User Interfaces Android - Graphical User Interfaces


Getting ready to create MVC conforming solutions MVC Pattern: The View - User Interfaces (GUis)
The Android developer should be aware of Android graphical interfaces are usually implemented as XML files (although
they could also be dynamically created from Java code).
• Inputs could be sent to the application from various physical/logical
components. Reacting to those signals is typically handled by callback An Android UI is conceptually similar to a common HTML page
methods. Usually there are many of them, you want to learn how to
choose the appropriate one. • In a manner similar to a web page interaction, when the Android user
touches the screen, the controller interprets the input and determines
• Moving to states in the lifecycle is tied to logic in the model. For instance, what specific portion of the screen and gestures were involved. Based on
if forced to Pause you may want to save uncommitted data. this information it tells the model about the interaction in such a way
that the appropriate “callback listener” or lifecycle state could be called
• A notification mechanism is used to inform the user of important events into action.
happening outside the current application (such as arrival of a text
message or email, low battery, fluctuations of the stock market, etc) and • Unlike a web application (which refreshes its pages after explicit
consequently choose how to proceed. requests from the user) an asynchronous Android background service
could quietly notify the controller about some change of state (such as
• Views are unlimited in terms of aesthetic and functionality. However reaching a given coordinate on a map) and in turn a change of the view’s
physical constraints such as size, and hardware acceleration (or lack of) state could be triggered; all of these without user intervention.
may affect how graphical components are managed.
4-3 4-4
Android - Graphical User Interfaces Android - Graphical User Interfaces
Android UI Design Patterns The VIEW Class
• The View class is the Android’s most basic component from which users
For a discussion of the newest Android UI Design Patterns (2013) see video:
interfaces can be created. It acts as a container of displayable elements.
https://www.youtube.com/watch?v=Jl3-lzlzOJI
• 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 structured containers used for


holding other Views and nested layouts.

A collection of weekly instructional videos made by the same presenters can be


obtained from the page (visited on Sept 6, 2014)
https://www.youtube.com/results?search_query=android+design+in+action
4-5 4-6

Android - Graphical User Interfaces Android - Graphical User Interfaces


Using XML Nesting XML Layouts
<RelativeLayout
to represent UIs xmlns:android="http://schemas.android.com/apk/res/android"
• An Android’s XML view file consists of a layout design holding a
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" hierarchical arrangement of its contained elements.
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin" • The inner elements could be basic widgets or user-defined nested
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
layouts holding their own viewgroups.
android:paddingTop="@dimen/activity_vertical_margin" • An Activity uses the setContentView(R.layout.xmlfilename)
tools:context="csu.matos.gui_demo.MainActivity" >
method to render a view on the device’s screen.
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
<LinearLayout
android:layout_height="wrap_content"
android:layout_alignParentTop="true" xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_centerHorizontal="true" android:layout_width="match_parent"
android:layout_marginTop="36dp" android:layout_height="wrap_content"
android:text="@string/edit_user_name" android:orientation="horizontal" >
android:ems="12" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button1" Widgets and other nested layouts
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
Actual UI displayed by the app android:layout_centerHorizontal="true"
android:layout_marginTop="48dp" </LinearLayout>
Text version: activity_main.xml file android:text="@string/btn_go" />
⟶ </RelativeLayout>
4-7 4-8
Android - Graphical User Interfaces Android - Graphical User Interfaces
Setting Views to Work A Sample of Common Android LAYOUTS
Dealing with widgets & layouts typically involves the following operations

1. Set properties: For instance, when working with a TextView you set
the background color, text, font, alignment, size, padding, margin,
etc.

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(…).


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.
4-9 Reference: http://developer.android.com/guide/topics/ui/layout-objects.html
4 - 10

Android - Graphical User Interfaces Android - Graphical User Interfaces


A Sample of Common Android WIDGETS A Sample of Common Android WIDGETS
WebView

GalleryView

TabWidget

MapView
Spinner

AutoCompleteTextView ListView
TimePicker Form Controls It is a version of the EditText A ListView is a View that
Includes a variety of typical widget that will provide shows items in a vertically
AnalogClock
form widgets, like: auto-complete suggestions scrolling list. The items are
DatePicker as the user types. The acquired from a ListAdapter.
A DatePicke is a widget image buttons,
text fields, suggestions are extracted
that allows the user to from a collection of strings.
select a month, day and checkboxes and
year. radio buttons.
Reference: http://developer.android.com/guide/topics/ui/layout-objects.html
Reference: http://developer.android.com/guide/topics/ui/layout-objects.html 4 - 11 4 - 12
Android - Graphical User Interfaces Android - Graphical User Interfaces
GUI Editing: XML Version GUI Editing: XML Version
Android considers XML-based layouts to be resources, consequently layout files Android considers XML-based layouts to be resources, consequently layout files
are stored in the res/layout directory inside your Android project. are stored in the res/layout directory inside your Android project.

Package App
Explorer explorer

Resource
folder
Resource
folder

XML version XML version


of a window of a window

4 - 13 4 - 14

Android - Graphical User Interfaces Android - Graphical User Interfaces


GUI Editing: WYSIWYG Version Aside… Tools you can use to create an Android GUI
The Screen Designer Tool included in Eclipse+ADT allows you to operate each
Alternative tools for creating Android apps and GUIs:
screen using either a WYSIWIG or XML editor.
• Android Studio. Based on IntelliJ IDEA IDE. Functionally equivalent to Eclipse
with the ADT Plugin.
http://developer.android.com/sdk/installing/studio.html

• Android SDK. Streamlined workbench based on Eclipse+ADT in a simpler to


install package. http://developer.android.com/sdk/index.html
Screen’s
Outline
• NBAndroid. Workbench based on NetBeans+ADT.
http://www.nbandroid.org/2014/07/android-plugin-for-gradle-011012.html
GUI
Palette

Widget’s
• DroidDraw Very simple GUI designer, incomplete, not integrated to the
properties Eclipse IDE, aging! http://www.droiddraw.org/

• App Inventor (educational, very promising & ambitious, ‘hides’ coding …)


http://appinventor.mit.edu/
Select
WYSIWYG or
XML view 4 - 15 4 - 16
WYSIWYG screen
Android - Graphical User Interfaces Android - Graphical User Interfaces
GUI Elements: The LAYOUT FrameLayout
• Android GUI Layouts are containers having a predefined structure and • The FrameLayout is the simplest type of GUI container.
placement policy such as relative, linear horizontal, grid-like, etc.
• It is useful as an outermost container holding a window.
• Layouts can be nested, therefore a cell, row, or column of a given layout
could be another layout. • Allows you to define how much of the screen (high,
width) is to be used.
• The Eclipse+ADT workbench offers the following base types:
• All its children elements are aligned to the top left corner
of the screen.;

4 - 17 4 - 18

Android - Graphical User Interfaces Android - Graphical User Interfaces


LinearLayout LinearLayout
• The LinearLayout supports a filling strategy in which new elements are Setting Attributes
stacked either in a horizontal or vertical fashion.

• If the layout has a vertical orientation new rows are placed one on top of Configuring a LinearLayout usually requires you to set the following attributes:
the other.
• orientation (vertical, horizontal)
• A horizontal layout uses a side-by-side column placement policy. • fill model (match_parent, wrap_contents)
• weight (0, 1, 2, …n )
• gravity (top, bottom, center,…)
• padding ( dp – dev. independent pixels )
• margin ( dp – dev. independent pixels )

4 - 19 4 - 20
Android - Graphical User Interfaces Android - Graphical User Interfaces
LinearLayout : Orientation <LinearLayout
xmlns:android="http://schemas.android.com/ap
LinearLayout : Fill Model
k/res/android"
The android:orientation property android:id="@+id/myLinearLayout" • Widgets have a "natural size“ based on their included text (rubber band
can be set to: horizontal for columns, or android:layout_width="match_parent" effect).
android:layout_height="match_parent"
vertical for rows. android:orientation="horizontal" • On occasions you may want your widget to have a specific space
android:padding="4dp" >
Use setOrientation() for runtime allocation (height, width) even if no text is initially provided (as is the
<TextView
changes. android:id="@+id/labelUserName" case of the empty text box shown below).
horizontal android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffff0000" natural sizes
android:text=" User Name " empty screen space
android:textColor="#ffffffff"
android:textSize="16sp"
android:textStyle="bold" />

<EditText
android:id="@+id/ediName"
v android:layout_width="wrap_content"
e android:layout_height="wrap_content"
r android:text="Maria Macarena" Shown on a
t android:textSize="18sp" /> Gingerbread
i <Button device
c android:id="@+id/btnGo"
a android:layout_width="wrap_content"
l android:layout_height="wrap_content"
android:text="Go"
android:textStyle="bold" />
Shown on a Kitkat device </LinearLayout>
421
- 21 4 - 22

Android - Graphical User Interfaces Android - Graphical User Interfaces


LinearLayout : Fill Model LinearLayout : Fill Model
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
All widgets inside a LinearLayout must include ‘width’ and ‘height’ attributes. android:id="@+id/myLinearLayout"
125 dp
android:layout_width="match_parent"
entire row android:layout_height="match_parent"
android:layout_width (320 dp on medium resolution screens)
android:background="#ff0033cc"
android:orientation="vertical"
android:layout_height android:padding="6dp" >
Row-wise

<TextView
android:id="@+id/labelUserName"
android:layout_width="match_parent" Use all the row
Values used in defining height and width can be: android:layout_height="wrap_content"
android:background="#ffff0066"
1. A specific dimension such as 125dp (device independent pixels dip ) android:text="User Name"
android:textColor="#ff000000"
android:textSize="16sp"
android:textStyle="bold" />
2. wrap_content indicates the widget should just fill up its natural space.
<EditText
android:id="@+id/ediName"
android:layout_width="match_parent"
3. match_parent (previously called ‘fill_parent’) indicates the widget wants android:layout_height="wrap_content"
android:textSize="18sp" />
to be as big as the enclosing parent.
<Button
android:id="@+id/btnGo" Specific size: 125dp
android:layout_width="125dp"
Medium resolution is: 320 x 480 dpi. android:layout_height="wrap_content"
Shown on a Gingerbread device android:text="Go"
android:textStyle="bold" />
4 - 23 </LinearLayout> 4 - 24
Android - Graphical User Interfaces Android - Graphical User Interfaces
Warning ! Same XML different rendition… LinearLayout : Weight
Since the introduction of Android The extra space left unclaimed in a layout could be assigned to
4.x, changes in the SDK make any of its inner components by setting its Weight attribute.
layouts to be more uniformly Use 0 if the view should not be stretched. The bigger the weight
displayed in all 4.x and newer the larger the extra space given to that widget.
devices (the intention is to provide
a seamless Android experience Example
The XML specification for this window is
independent from provider,
similar to the previous example.
hardware, and developer).
Kitkat
The TextView and Button controls have
The XML spec used in the previous the additional property
example looks different when Takes: 2 /(1+1+2)
displayed on a 4.x and older android:layout_weight="1" of the screen space
devices (see figures on the right, Same XML layout shown on a
please also notice the color whereas the EditText control has
Gingerbread (left) and Kitkat (right) device.
bleeding occurring on top of the
android:layout_weight="2"
GO button, more on this issue in
the Appendix) Remember, default value is 0
4 - 25 Gingerbread 4 - 26

Android - Graphical User Interfaces Android - Graphical User Interfaces


LinearLayout : Gravity LinearLayout : Padding
• Gravity is used to indicate how a control will align on the screen.
• By default, widgets are left- and top-aligned. • The padding attribute specifies the widget’s internal margin (in dp units).
• You may use the XML property android:layout_gravity="…"
to set other possible arrangements: left, center, right, top, bottom, etc. • The internal margin is the extra space between the borders of the widget's
"cell" and the actual widget contents.

• Either use
• android:padding property
Button has
• or call method setPadding() at runtime.
right
layout_gravity
The ‘blue’ surrounding space
Hello world around the text represents
the inner view’s padding

4 - 27 4 - 29
Android - Graphical User Interfaces Android - Graphical User Interfaces
LinearLayout : Padding and Margin LinearLayout : Set Internal Margins Using Padding
Padding and Margin represent the internal and external spacing between a Example:
widget and its included and surrounding context (respectively). The EditText box has been changed to include 30dp of padding all around

<EditText
android:id="@+id/ediName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="30dp" />

...

4 - 30 4 - 31

Android - Graphical User Interfaces Android - Graphical User Interfaces


LinearLayout : Set External Margins Relative Layout
• Widgets –by default– are closely displayed next to each other. The placement of a widget in a RelativeLayout is based on its positional
• To increase space between them use the android:layout_margin relationship to other widgets in the container as well as the parent container.
attribute

Increased inter-widget space


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
<EditText
android:id="@+id/ediName"
B C
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_margin="6dp"
>
</EditText>
Using default spacing between
widgets
...
4 - 32 4 - 33
Android - Graphical User Interfaces Android - Graphical User Interfaces
Relative Layout - Example: Using Eclipse+ADT WYSIWYG Editor Relative Layout - Referring to the container
Below there is a sample of various positioning XML boolean properties
(true/false) which are useful for collocating a widget based on the location of
its parent container.

android:layout_alignParentTop
android:layout_alignParentBottom

android:layout_alignParentLeft
android:layout_alignParentRight

android:layout_centerInParent
android:layout_centerVertical
android:layout_centerHorizontal

Location of the button is expressed


in reference to its relative position
with respect to the EditText box.

4 - 34 4 - 35

Android - Graphical User Interfaces Android - Graphical User Interfaces


Relative Layout - Referring to Other Widgets Relative Layout - Referring to Other Widgets – WYSIWYG Editor
Example1: The image shows a screen designed with the WYSIWYG Editor. We
are trying to collocate the button
android:layout_alignTop=“@+id/wid1” wid1 wid2 identified as wid2. Observe that its
placement is visually described
using (green) lines referencing the
already drawn wid1 view. Both views
android:layout_alignBottom =“@+id/wid1” wid1 wid2 have same bottom, same right, but
wig2 has an elevation of 36 dps
respect wid1.

wid1 <Button
android:layout_alignLeft=“@+id/wid1” android:id="@+id/wid2"
wid2 android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/wid1"
wid1 android:layout_alignRight="@+id/wid1"
android:layout_alignRight=“@+id/wid1” android:layout_marginBottom="36dp"
wid2 android:text="@string/wid2" />
4 - 36 4 - 37
Android - Graphical User Interfaces Android - Graphical User Interfaces
Relative Layout - Referring to Other Widgets – WYSIWYG Editor Relative Layout - Example2
<RelativeLayout
When using relative positioning you need to: xmlns:android="http://schemas.android.com/apk/r <EditText
es/android" android:id="@+id/txtUserName"
android:id="@+id/myRelativeLayout" android:layout_width="match_parent"
android:layout_width="match_parent" android:layout_height="wrap_content"
1. Use identifiers ( android:id attributes ) on all elements that you will android:layout_height="match_parent" android:layout_alignParentLeft="true"
be referring to. android:background="#ff000099" > android:layout_below="@+id/lblUserName"
android:padding="20dp" >
<TextView </EditText>
android:id="@+id/lblUserName"
2. XML elements are named using the prefix: @+id/... For instance android:layout_width="match_parent" <Button
android:layout_height="wrap_content" android:id="@+id/btnGo"
an EditText box could be called: android:id="@+id/txtUserName" android:layout_alignParentLeft="true" android:layout_width="wrap_content"
android:layout_alignParentTop="true" android:layout_height="wrap_content"
android:background="#ffff0066"
3. You must refer only to widgets that have been already defined. For android:text="User Name" android:layout_alignRight="@+id/txtUserName"
android:textColor="#ff000000" android:layout_below="@+id/txtUserName"
instance a new control to be positioned below the txtUserName EditText android:textStyle="bold" > android:text="Go"
</TextView> android:textStyle="bold" >
box could refer to it using: </Button>
android:layout_below="@+id/txtUserName" <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>
4 - 38 </RelativeLayout> 439
- 39

Android - Graphical User Interfaces Android - Graphical User Interfaces


Table Layout Table Layout – Setting Number of Columns
1. Android's TableLayout uses a grid template to position your widgets.
2. Like in a 2D matrix, cells in the grid are identified by rows and columns. The final number of columns in a table is determined by Android.
3. Columns are flexible, they could shrink or stretch to accommodate their
contents. Example:
4. The element TableRow is used to define a new row in which widgets can If your TableLayout have three rows
be allocated. • one row with two widgets,
5. The number of columns in a TableRow is determined by the total of side- • one with three widgets, and
by-side widgets placed on the row. • one final row with four widgets,
there will be at least four columns in the table, with column indices: 0, 1, 2, 3.

0 1

0 1 2

0 1 2 3

4 - 40 4 - 41
Android - Graphical User Interfaces Android - Graphical User Interfaces
Table Layout – Example 3 Table Layout – Example 3 continuation
<TableLayout
<TableRow>
The screen shows various items from xmlns:android="http://schemas.android.com/apk/r
a McDonald’s restaurant menu [*]. es/android" <TextView
android:id="@+id/myTableLayout" android:text="Big Mac" />
android:layout_width="match_parent" <TextView
The TableLayout has four TableRows, android:layout_height="match_parent" android:gravity="center"
android:orientation="vertical" android:text="530" />
with three columns in the first row android:padding="6dp" > <TextView
(labels) and four cells in each of the android:gravity="center"
<TableRow> android:text="3.99" />
other three rows (item, Calories, <TextView <Button
Price, and Buy button). android:background="#FF33B5E5" android:id="@+id/btnBuyBigMac"
android:text="Item " /> android:gravity="center"
<TextView android:text="Buy" />
android:layout_marginLeft="5dp" </TableRow>
android:background="#FF33B5E5"
android:text="Calories " /> <View
android:layout_height="1dp"
<TextView android:background="#FF33B5E5" />
android:layout_marginLeft="5dp"
android:background="#FF33B5E5" <!-- other TableRows ommitted --!>
android:text="Price $ " />
</TableRow>
</TableLayout>
<View
[*] Reference: Pages visited on Sept 8, 2014 android:layout_height="1dp"
http://nutrition.mcdonalds.com/getnutrition/nutritionfacts.pdf android:background="#FF33B5E5" />

http://hackthemenu.com/mcdonalds/menu-prices/ 4 - 42 4 - 43

Android - Graphical User Interfaces Android - Graphical User Interfaces


Table Layout – Stretching a Column Table Layout – Stretching a Column
• A single widget in a TableLayout can occupy more than one column. Widgets on a table’s row are placed lexicographically from left to right,
beginning with the first available column. Each column in the table stretches
• The android:layout_span property indicates the number of columns as needed to accommodate its occupants.
the widget is allowed to expand.
Example 4:
• The table shown below has four columns (indices: 0,1,2,3).
<TableRow> • The label (“ISBN”) goes in the first column (index 0).
<TextView • The EditText to the right of the label uses the layout_span attribute to
android:text="URL:" /> be placed into a spanned set of three columns (columns 1 through 3).
<EditText android:layout_span="3"
android:id="@+id/txtData"
android:layout_span="3" />
Label EditText EditText-span EditText-span
</TableRow>
(ISBN)
Column 0 Column 1 Column 2 Column 3
Button Button
Cancel OK

4 - 44 android:layout_column="2" 4 - 45
Android - Graphical User Interfaces Android - Graphical User Interfaces
Table Layout – Example 4 continuation Table Layout – Stretching the Entire Table
• By default, a column is as wide as the “natural’ size of the widest widget
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
collocated in this column (e.g. a column holding a button showing the
xmlns:android="http://schemas.android.com/apk/res/android" caption “Go” is narrower than other column holding a button with the
android:id="@+id/myTableLayout"
android:layout_width="match_parent" caption “Cancel”).
android:layout_height="match_parent"
android:padding="6dp"
android:orientation="vertical" > • A table does not necessarily take all the horizontal space available.
<TableRow>
<TextView android:text="ISBN:" />
<EditText
android:id="@+id/ediISBN"
• If you want the table to (horizontally) match its container use the
Occupy 3
android:layout_span="3" /> property:
</TableRow> columns
<TableRow>
<Button
android:stretchColumns=“column(s)”
android:id="@+id/cancel"
android:layout_column="2"
android:text="Cancel" /> Where ‘column(s)’ is the column-index (or comma-separated column
<Button Skip
android:id="@+id/ok"
indices) to be stretched to take up any space still available on the row.
Note to the reader: android:text="OK" /> columns 0, 1 For example, to stretch columns 0, and 2 of a table you set
</TableRow>
Experiment changing android:stretchColumns=“0,2”
layout_span to 1, 2, 3 </TableLayout>

4 - 46 4 - 47

Android - Graphical User Interfaces Android - Graphical User Interfaces


Table Layout – Stretching the Entire Table ScrollView Layout (Vertical & Horizontal)
In Example 4 we created a table with four columns. We may elongate its • The ScrollView control is useful
columns 2, 3 to force the TableLayout to horizontally occupy the empty rest of in situations in which we have
the screen. Observe the use of the clause ‘:strechColumns’ more data to show than what a Scroller
... single screen could display. indicator
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android" • ScrollViews provide a vertical
android:id="@+id/myTableLayout" sliding (up/down) access to the
android:layout_width="match_parent"
android:layout_height="match_parent"
data.
android:orientation="vertical"
android:stretchColumns="2,3" • The HorizontalScrollView
> provides a similar left/right
… sliding mechanism)

• Only a portion of the user’s data


can be seen at one time,
however the rest is available for
Screens shown before and after using the android:stretchColumns clause. viewing.
4 - 48 4 - 49
Android - Graphical User Interfaces Android - Graphical User Interfaces
Example 5. Vertical ScrollView Layout Example 6. HorizontalScrollView Layout
<TextView <TextView
android:id="@+id/textView2" <HorizontalScrollView android:id="@+id/textView2"
<ScrollView android:layout_width="match_parent" android:layout_width="match_parent"
xmlns:android= android:layout_height="wrap_content" xmlns:android="http://schemas.android.com/apk/r android:layout_height="wrap_content"
"http://schemas.android.com/apk/res/android" android:text="Item2" es/android" android:text="Item2"
android:id="@+id/myVerticalScrollView1" android:textSize="150sp" /> android:id="@+id/myHorizontalScrollView1" android:textSize="75sp" />
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" > <View android:layout_height="wrap_content" > <View
android:layout_width="match_parent" android:layout_width="6dp"
<LinearLayout android:layout_height="6dp" <LinearLayout android:layout_height="match_parent"
android:id="@+id/myLinearLayoutVertical" android:background="#ffff0000" /> android:id="@+id/myLinearLayoutVertical" android:background="#ffff0000" />
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" <TextView android:layout_height="match_parent" <TextView
android:orientation="vertical" > android:id="@+id/textView3" android:orientation="horizontal" > android:id="@+id/textView3"
android:layout_width="match_parent" android:layout_width="match_parent"
<TextView android:layout_height="wrap_content" <TextView android:layout_height="wrap_content"
android:id="@+id/textView1" android:text="Item3" android:id="@+id/textView1" android:text="Item3"
android:layout_width="match_parent" android:textSize="150sp" /> android:layout_width="match_parent" android:textSize="75sp" />
android:layout_height="wrap_content" android:layout_height="wrap_content" </LinearLayout>
android:text="Item1" </LinearLayout> android:text="Item1"
android:textSize="150sp" /> android:textSize="75sp" /> </HorizontalScrollView>
</ScrollView> <View
<View android:layout_width="6dp"
android:layout_width="match_parent" android:layout_height="match_parent"
android:layout_height="6dp" android:background="#ffff0000" />
android:background="#ffff0000" />

4 - 50 4 - 51

Android - Graphical User Interfaces Android - Graphical User Interfaces


Miscellaneous: Absolute Layout (Deprecated) Example 7. Absolute Layout (Deprecated)
<?xml version="1.0" encoding="utf-8"?>
• This layout lets you specify exact <AbsoluteLayout
android:id="@+id/myLinearLayout" </TextView>
locations (x/y coordinates) of its android:layout_width="match_parent" <EditText
children. android:layout_height="match_parent" android:id="@+id/etName"
android:background="#ff0033cc" android:layout_width="match_parent"
android:padding="4dp" android:layout_height="wrap_content"
• Absolute layouts are less flexible xmlns:android="http://schemas.android.co android:textSize="18sp"
m/apk/res/android" android:layout_x="0dp"
and harder to maintain than > android:layout_y="38dp"
>
other types of layouts without <TextView </EditText>
absolute positioning. android:id="@+id/tvUserName"
android:layout_width="match_parent" <Button
android:layout_height="wrap_content" android:layout_width="120dp"
• They DO NOT migrate well from android:background="#ffff0066" android:text="Go"
android:text="User Name" android:layout_height="wrap_content"
one device to the other; not even android:textSize="16sp" android:textStyle="bold"
from portrait to landscape modes android:textStyle="bold" android:id="@+id/btnGo"
android:textColor="#ff000000" android:layout_x="100dp"
in the same device! android:layout_x="0dp" android:layout_y="170dp" />
android:layout_y="10dp" </AbsoluteLayout>
>

4 - 52 4 - 53
Android - Graphical User Interfaces Android - Graphical User Interfaces
Connecting Layouts to Java Code Connecting Layouts to Java Code
PLUMBING.
You must ‘connect’ functional XML elements –such as buttons, text boxes, Java code
package csu.matos.gui_demo;
check boxes- with their equivalent Java objects. This is typically done in the import android…;
onCreate(…) method of your main activity. After all the connections are
public class MainActivity extends Activity {
made and programmed, your app should be ready to interact with the user.
EditText edtUserName;

XLM Layout <!– XML LAYOUT --> Button btnGo;


<LinearLayout
<xml…. android:id="@+id/myLinearLayout" @Override
... ... > protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
... <TextView
</xml> android:text="ACME Login Screen" setContentView(R.layout.activity_main);
... />
edtUserName = (EditText) findViewById(R.id.edtUserName);
<EditText
android:id="@+id/edtUserName" btnGo = (Button) findViewById(R.id.btnGo);
JAVA code ... /> ...
public class ... }
<Button
{ android:id="@+id/btnGo"
... ... /> ...
}
... </LinearLayout>
} 4 - 54 4 - 55

Android - Graphical User Interfaces Android - Graphical User Interfaces


What is the meaning of an Android Context? Connecting Layouts to Java Code

An Aside Assume the UI in res/layout/activity_main.xml has been created. This layout


could be called by an application using the statement
On Android, a Context defines a logical workspace on which an app can load
and access resources. setContentView(R.layout.activity_main);

• When a widget is created, it is attached to a particular Context. By means Individual XML defined widgets, such as btnGo is later associated to the Java
of its affiliation to that environment, it then could access other members application using the statement findViewByID(...) as in
of the hierarchy on which it has been collocated.
Button btnGo= (Button) findViewById(R.id.btnGo);
• For a simple ‘one activity app’ -say MainActivity- the method
getApplicationContext() and the reference MainActivity.this return the Where R is a class automatically generated to keep track of resources
same result. available to the application. In particular R.id... is the collection of widgets
defined in the XML layout (Use Eclipse’s Package Explorer, look at your
• An application could have several activities. Therefore, for a multi- /gen/package/R.java contents).
activity app we have one app context, and a context for each of its
A Suggestion: The widget’s identifiers used in the XML layout and Java code could be the
activities, each good for accessing what is available in that context. same. It is convenient to add a prefix to each identifier indicating its nature. Some options are
txt, btn, edt, rad, chk, etc. Try to be consistent.
4 - 56 4 - 57
Android - Graphical User Interfaces Android - Graphical User Interfaces
Connecting Layouts to Java Code Basic Widgets: TextViews
Attaching Listeners to Widgets • In Android a label or text-box is called
a TextView.
Consider the screen on the right. To make its
‘Go’ button widget be responsive to the • A TextView is typically used for showing
user’s pushing of that button, we may add a a caption or a text message.
listener for the click event. • TextViews are not editable, therefore
they take no input.
Button btnGo = (Button) findViewById(R.id.btnGo);
• The text to be shown may include the
btnGo.setOnClickListener(new OnClickListener() { \n formatting character (newLine)
@Override
• You may also use HTML formatting by
public void onClick(View v) {
// get userName and validate against some database
setting the text to:
// put some more logic here... Html.fromHtml("<b>bold</b> string")
}
});

Note: Other common ‘listeners’ watch for events such as: textChanged, For a ‘colorful’ rendition of the ‘99 Bottles of Beer’
song see:
tap, long-press, select, focus, etc. 4 - 58 https://www.youtube.com/watch?v=3KnpZYkTWno

Android - Graphical User Interfaces Android - Graphical User Interfaces


Basic Widgets: Example 8 - TextViews Basic Widgets: Buttons
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
• A Button widget allows the simulation of a GUI clicking action.
android:layout_height="match_parent" • Button is a subclass of TextView. Therefore formatting a button’s face is
android:orientation="vertical"
android:padding="6dp" > similar to the setting of a TextView.
<TextView
• You may alter the default behavior of a button by providing a custom
android:id="@+id/textView1" drawable.xml specification to be applied as background. In those specs
android:layout_width="match_parent"
android:layout_height="wrap_content" you indicate the shape, color, border, corners, gradient, and behavior
android:background="@color/holo_blue_bright"
android:text="(Lyrics) 99 Bottles of Beer"
based on states (pressed, focused). More on this issue in the appendix.
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView <Button
android:id="@+id/textView2" android:id="@+id/btnClickMeNow"
android:layout_width="match_parent" android:layout_width="120dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:layout_gravity="center"
android:background="@color/gray_light"
android:text="\n\t99 bottles of beer on the wall, 99 bottles of beer.Take one down and android:layout_marginTop="5dp“
pass it around, 98 bottles of beer on the wall.\n\n\t98 bottles of beer on the wall, 98 bottles android:gravity="center"
of beer.Take one down and pass it around, 97 bottles of beer on the wall. \n\n\t97 bottles of android:padding="5dp"
beer on the wall, 97 bottles of beer.Take one down and pass it around, 96 bottles of beer on android:text="Click Me Now!"
the wall... " android:textColor="#ffff0000"
android:textSize="14sp" />
android:textSize="20sp"
</LinearLayout> android:textStyle="bold" />

4 - 60 4 - 61
Android - Graphical User Interfaces Android - Graphical User Interfaces
Example9: Connecting Multiple Buttons This example shows an Example9: Connecting Multiple Buttons [Layout]
alternative way of
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
wiring-up multiple
public class MainActivity extends Activity implements OnClickListener { xmlns:tools="http://schemas.android.com/tools"
TextView txtMsg; buttons. Observe how android:layout_width="match_parent"
Button btnBegin; the main activity android:layout_height="match_parent"
Button btnExit; android:orientation="vertical"
implements the
@Override android:padding="6dp" >
public void onCreate(Bundle savedInstanceState) { OnClickListener
super.onCreate(savedInstanceState); interface. <TextView
setContentView(R.layout.activity_main ); android:id="@+id/txtMsg"
The mandatory onClick
android:layout_width="match_parent"
txtMsg = (TextView) findViewById(R.id.txtMsg); method checks which of android:layout_height="wrap_content"
btnBegin = (Button) findViewById(R.id.btnBegin); the many buttons sent android:background="#88eed0d0" />
btnExit = (Button) findViewById(R.id.btnExit);
the signal and proceeds
<Button
btnBegin.setOnClickListener(this); from there. android:id="@+id/btnBegin"
btnExit.setOnClickListener(this); android:layout_width="wrap_content"
}//onCreate android:layout_height="wrap_content"
android:ems="5"
android:text="Begin" />
@Override
public void onClick(View v) { <Button
if (v.getId() == btnBegin.getId()) { android:id="@+id/btnExit"
txtMsg.setText("1-You clicked the 'BEGIN' button"); android:layout_width="wrap_content"
} android:layout_height="wrap_content"
if (v.getId() == btnExit.getId()) { android:ems="5"
txtMsg.setText("2-You clicked the 'EXIT' button"); android:text="Exit" />
}
</LinearLayout>
}//onClick
} 4 - 62 4 - 63

Android - Graphical User Interfaces Android - Graphical User Interfaces


Basic Widgets: ImageView & ImageButton Basic Widgets: ImageView & ImageButton
• ImageView and ImageButton allow the embedding
of images in your applications ( gif, jpg, png, etc). <LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
• Analogue to TextView and Button controls android:layout_height="match_parent"
android:padding="6dp"
(respectively). android:orientation="vertical" >

<ImageButton
• Each widget takes an android:id="@+id/imgButton1"
android:src or android:layout_width="wrap_content"
android:background android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" >
attribute (in an XML layout) to specify what picture </ImageButton>
to use.
<ImageView
android:id="@+id/imgView1"
• Pictures are stored in the res/drawable folder android:layout_width="200dp"
android:layout_height="150dp"
(optionally a medium, high, x-high, xx-high, and xxx- android:scaleType="fitXY"
high respectively definition version of the same android:src="@drawable/flowers1" >
image could be stored for later usage with different </ImageView>

types of screens). Details available at: </LinearLayout>


http://developer.android.com/design/style/iconography.html
4 - 65
Android - Graphical User Interfaces Android - Graphical User Interfaces
Basic Widgets: Buttons - Combining Images & Text Basic Widgets: How icons are used in Android?
mdpi (761 bytes)
A common Button widget could display text and Icons are small images used to graphically represent 1x = 48 x 48 pixels
a simple image as shown below your application and/or parts of it. They may appear BaseLine
in different parts of your app including: hdpi (1.15KB)
<LinearLayout
. . . 1.5x = 72 x 72 px
• Home screen
<Button • Launcher window.
android:layout_width="wrap_content" • Options menu x-hdpi (1.52KB)
android:layout_height="wrap_content" • Action Bar 2x = 96 x 96 px
android:drawableLeft="@drawable/ic_launcher" • Status bar
android:gravity="left|center_vertical" • Multi-tab interface.
android:padding="15dp"
• Pop-up dialog boxes
android:text="Click me" />
• List view
</LinearLayout> xx-hdpi (2.47KB)
Detailed information on Android’s iconography is available 3x = 144 x 144 px

at: http://developer.android.com/design/style/iconography.html
HINT: Several websites allow you to convert for free your
pictures to image-files under a variety of formats and sizes
such as png, .jpg, .gif, etc. For instance try:
http://www.prodraw.net/favicon/index.php
http://converticon.com/
4 - 66 4 - 67

Android - Graphical User Interfaces Android - Graphical User Interfaces


Basic Widgets: EditText Boxes Basic Widgets: EditText Boxes
• The EditText widget is an extension of Input Type Formats
TextView that allows user’s input. An EditText box could be set to accept input strings
satisfying a particular pattern such as: numbers
• In addition to plain text, this widget (with and without decimals or sign), phones, dates,
can display editable text formatted times, uris, etc.
with HTML-styles such as bold, italics,
underline, etc ). This is done with Setting the EditText box to accept a particular
Html.fromHtml(html_text) choice of data-type, is done through the XML clause

• Moving data in and out of an EditText android:inputType=“choices”


box is usually done in Java through the
following methods: where choices include any of the single values
shown in the figure. You may combine types, for
txtBox.setText(“someValue”) instance: textCapWords|textAutoCorrect
Accepts text that capitalizes every word, incorrect
txtBox.getText().toString() words are automatically changed (for instance ‘teh‘
is converted into ‘the’, and so on.
4 - 68 4 - 69
Android - Graphical User Interfaces Android - Graphical User Interfaces
Example10: Login-Screen Example10: Login-Screen
In this example we will create a simple login screen holding a label (TexView), a LAYOUT 1 of 2
textBox (EditText), and a Button. When the EditTex box gains focus, the system <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
provides a virtual keyboard customized to the input-type given to the entry box android:layout_width="match_parent"
android:layout_height="match_parent"
(capitals & spelling). Clicking the button displays a Toast-message that echoes the android:orientation="vertical"
supplied user-name. android:padding="6dp" >

<TextView
android:id="@+id/txtLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_light"
android:text="@string/ACME_Login_Screen"
android:textSize="20sp"
android:textStyle="bold" />
Capitals & Setting
Hint spelling text <EditText
Disable android:id="@+id/edtUserName"
button android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
A brief android:hint="@string/Enter_your_First_and_Last_name"
message box android:inputType="textCapWords|textAutoCorrect"
android:textSize="18sp" >
<requestFocus />
</EditText>

4 - 70 4 - 71
Images from an HTC-One device

Android - Graphical User Interfaces Android - Graphical User Interfaces


Example10: Login-Screen Example10: Login-Screen - MainActivity 1 of 3

LAYOUT 2 of 2
public class MainActivity extends ActionBarActivity {

<Button // class variables representing UI controls to be controlled from the Java program
android:id="@+id/btnLogin" TextView txtLogin;
android:layout_width="82dp" EditText edtUserName;
android:layout_height="wrap_content" Button btnLogin;
android:layout_marginTop="2dp"
android:text="@string/login" /> // variables used with the Toast message class
</LinearLayout> private Context context;
private int duration = Toast.LENGTH_SHORT;

@Override
res/values/strings.xml public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
<?xml version="1.0" encoding="utf-8"?>
// show the login screen
<!-- this is the res/values/strings.xml file -->
setContentView(R.layout.activity_main);
<resources>
context = getApplicationContext();
<string name="app_name">GuiDemo</string>
// binding the UI's controls defined in "main.xml" to Java code
<string name="action_settings">Settings</string>
txtLogin = (TextView) findViewById(R.id.txtLogin);
<string name="login">login</string>
edtUserName = (EditText) findViewById(R.id.edtUserName);
<string name="ACME_Login_Screen">ACME Login Screen</string>
btnLogin = (Button) findViewById(R.id.btnLogin);
<string name="Enter_your_First_and_Last_name">Enter your First and Last name</string>

</resources>

4 - 72 4 - 73
Android - Graphical User Interfaces Android - Graphical User Interfaces
Example10: Login-Screen - MainActivity 2 of 3 Example10: Login-Screen - MainActivity 3 of 3

// LISTENER: allowing the button widget to react to user interaction


btnLogin.setOnClickListener(new OnClickListener() { @Override
@Override public boolean onCreateOptionsMenu(Menu menu) {
public void onClick(View v) { // Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
String userName = edtUserName.getText().toString(); Log.e used for return true;
}
Log.e("onClick ", "duration= " + duration); debugging –
Log.e("onClick ", "context= " + context.toString()); remove later!!! @Override
Log.e("onClick ", "userName= " + userName); public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
if (userName.equals("Maria Macarena")) { // as you specify a parent activity in AndroidManifest.xml.
txtLogin.setText("OK, please wait..."); int id = item.getItemId();
Toast.makeText(getApplicationContext(), if (id == R.id.action_settings) {
"Welcome " + userName, duration).show(); return true;
btnLogin.setEnabled(false); }
} else { return super.onOptionsItemSelected(item);
Toast.makeText(context, userName + " is not a valid USER", }
duration).show(); }
}
}
});// onClick

}// onCreate

4 - 74 4 - 75

Android - Graphical User Interfaces Android - Graphical User Interfaces


Programming … Basic Widgets: CheckBoxes
A checkbox is a special two-states button
Your turn! which can be either checked or unchecked.

(working as a minimalist developer) A screen may include any number of mutually


inclusive (independent) CheckBoxes. At any
time, more than one CheckBox in the GUI
Implement any/all of the following projects could be checked.
using simple UI controls (EditText, TextView,
buttons) In our “CaféApp” example, the screen on the
right displays two CheckBox controls, they are
1. Currency Exchange calculator used for selecting ‘Cream’ and ‘Sugar’ options.
In this image both boxes are ‘checked’.
2. Tip Calculator
3. Simple Flashlight When the user pushes the ‘Pay’ button a
Toast-message is issue echoing the current
combination of choices held by the
checkboxes.
4 - 76 4 - 77
Android - Graphical User Interfaces Android - Graphical User Interfaces
Example11: CheckBoxes – CaféApp [Layout 1 of 2] Example11: CheckBoxes – CaféApp [Layout 2 of 2]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout <CheckBox
xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/chkSugar"
android:layout_width="match_parent" android:layout_width="wrap_content"
android:layout_height="match_parent" android:layout_height="wrap_content"
android:padding="6dp" android:text="@string/sugar"
android:orientation="vertical" > android:textStyle="bold" />

<TextView <Button
android:id="@+id/labelCoffee" android:id="@+id/btnPay"
android:layout_width="match_parent" android:layout_width="153dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:background="#ff993300" android:text="@string/pay"
android:text="@string/coffee_addons" android:textStyle="bold" />
android:textColor="@android:color/white"
android:textStyle="bold" /> </LinearLayout>

<CheckBox
android:id="@+id/chkCream"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cream"
android:textStyle="bold" />
78
4 - 78 4 - 79

Android - Graphical User Interfaces Android - Graphical User Interfaces


Example11: CheckBoxes – CaféApp [@string/… ] Example11: CheckBoxes – CaféApp [Code 1 of 2]
public class MainActivity extends Activity {
Resources: res/values/strings
CheckBox chkCream;
<?xml version="1.0" encoding="utf-8"?> CheckBox chkSugar;
<resources> Button btnPay;
<string name="app_name">GuiDemo</string> @Override
<string name="action_settings">Settings</string> public void onCreate(Bundle savedInstanceState) {
<string name="click_me">Click Me</string> super.onCreate(savedInstanceState);
<string name="sugar">Sugar</string> setContentView(R.layout.activity_main);
<string name="cream">Cream</string>
<string name="coffee_addons">What else in your coffee?</string> //binding XMl controls with Java code
<string name="pay">Pay</string> chkCream = (CheckBox)findViewById(R.id.chkCream);
</resources> chkSugar = (CheckBox)findViewById(R.id.chkSugar);
btnPay = (Button) findViewById(R.id.btnPay);

4 - 80 4 - 81
Android - Graphical User Interfaces Android - Graphical User Interfaces
Example11: CheckBoxes – CaféApp [Code 2 of 2] Basic Widgets: CheckBoxes
• A radio button (like a CheckBox) is a two-states button that
//LISTENER: wiring button-events-&-code
btnPay.setOnClickListener(new OnClickListener() { can be either checked or unchecked.
@Override
public void onClick(View v) { • Logically related radio buttons are normally put together in a RadioGroup
String msg = "Coffee "; container. The container forces the enclosed radio buttons to behave as
if (chkCream.isChecked()) {
msg += " & cream ";
mutually exclusive selectors. That is, the checking of one radio button
} unchecks all the others.
if (chkSugar.isChecked()){
msg += " & Sugar";
} • Properties for font face, style, color, etc. are managed in a way similar to
Toast.makeText(getApplicationContext(), setting a TextView.
msg, Toast.LENGTH_SHORT).show();
//go now and compute cost...
• You may call the method isChecked() to see if a specific RadioButton is
}//onClick
});
selected, or change its state by calling toggle().

}//onCreate

}//class

4 - 82 4 - 83

Android - Graphical User Interfaces Android - Graphical User Interfaces


Example12: CheckBoxes – CaféApp [Layout] Example12: CheckBoxes – CaféApp [Layout]
Based on Example11 - Only new XML and Java code is shown
Example
<TextView
We extend the previous android:id="@+id/textView1" <RadioGroup
android:layout_width="match_parent" android:id="@+id/radioGroupCoffeeType"
CaféApp example by adding android:layout_height="wrap_content" android:layout_width="match_parent"
a RadioGroup control android:background="#ff993300" android:layout_height="wrap_content" >
android:text="@string/kind_of_coffee"
that allows the user to pick android:textColor="#ffffff" <RadioButton
one type of coffee from RadioGroup android:textStyle="bold" /> android:id="@+id/radDecaf"
android:layout_width="wrap_content"
three available options. android:layout_height="wrap_content"
android:text="@string/decaf" />

<RadioButton
android:id="@+id/radExpresso"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/expresso" />

<RadioButton
android:id="@+id/radColombian"
android:layout_width="wrap_content"
Summary of choices android:layout_height="wrap_content"
android:checked="true"
android:text="@string/colombian" />
</RadioGroup>

4 - 84 485
- 85
Android - Graphical User Interfaces Android - Graphical User Interfaces
Example12: CheckBoxes – CaféApp [MainActivity] Example12: CheckBoxes – CaféApp [MainActivity]
public class MainActivity extends Activity { // LISTENER: wiring button-events-&-code
btnPay.setOnClickListener(new OnClickListener() {
@Override
CheckBox chkCream;
public void onClick(View v) {
CheckBox chkSugar; String msg = "Coffee ";
Button btnPay; if (chkCream.isChecked())
msg += " & cream ";
RadioGroup radCoffeeType; if (chkSugar.isChecked())
RadioButton radDecaf; msg += " & Sugar";
RadioButton radExpresso;
// get selected radio button ID number
RadioButton radColombian; int radioId = radCoffeeType.getCheckedRadioButtonId();
@Override
// compare selected's Id with individual RadioButtons ID
public void onCreate(Bundle savedInstanceState) { if (radColombian.getId() == radioId)
super.onCreate(savedInstanceState); msg = "Colombian " + msg;
setContentView(R.layout.main); // similarly you may use .isChecked() on each RadioButton
if (radExpresso.isChecked())
chkCream = (CheckBox) findViewById(R.id.chkCream); msg = "Expresso " + msg;
// similarly you may use .isChecked() on each RadioButton
chkSugar = (CheckBox) findViewById(R.id.chkSugar);
if (radDecaf.isChecked())
btnPay = (Button) findViewById(R.id.btnPay); msg = "Decaf " + msg;
radCoffeeType = (RadioGroup) findViewById(R.id.radioGroupCoffeeType);
Toast.makeText(getApplicationContext(), msg, 1).show();
radDecaf = (RadioButton) findViewById(R.id.radDecaf); // go now and compute cost...
}// onClick
radExpresso = (RadioButton) findViewById(R.id.radExpresso);
});
radColombian = (RadioButton) findViewById(R.id.radColombian); }// onCreate

4 - 86 }// class 487


- 87

Android - Graphical User Interfaces Android - Graphical User Interfaces


Example12: CheckBoxes – CaféApp [MainActivity] Miscellaneous: Useful UI Attributes & Java Methods
Programming Note
XML Controls the focus sequence:
android:visibility true/false set visibility
radGroupradioId = (RadioGroup)findViewById(R.id.radioGroup1); android:background color, image, drawable
int radioId = radGroupradioId.getCheckedRadioButtonId(); Alternative you may also <requestFocus /> react to user’s interaction
manage a RadioGroup
switch (radioId) {
case R.id.radColombian: msg += " Colombian "; break; as follows (this is simpler Java methods
case R.id.radExpresso: msg += " Expresso "; break; because you don’t need myButton.requestFocus()
case R.id.radDecaf: msg += " Decaf "; break;
to define the individual
} myTextBox.isFocused()
RadioButtons
myWidget.setEnabled()
myWidget.isEnabled()

488
- 88 4 - 89
Appendix A. Using the @string resource

User A good programming practice in Android is NOT to directly enter literal strings as
immediate values for attribute inside xml files.

Interfaces For example, if you are defining a TextView to show a company headquarter’s
location, a clause such as android:text="Cleveland" should not be used
(observe it produces a Warning [I18N] Hardcoded string “Cleveland”,
should use @string resource )

Instead you should apply a two steps procedure in which


1. You write the literal string –say headquarter – in res/values/string.xml. Enter
<string name="headquarter">Cleveland</string>

2. Whenever the string is needed provide a reference to the string using the
notation @string/headquarter. For instance in our example you should enter
android:text="@string/headquarter"

WHY?
If the string is used in many places and its actual value changes we just update the
This image was made using the resource file entry once. It also provides some support for internationalization -easy to
Device Frame Generator, which is part of
change a resource string from one language to another.
the Android Asset Studio tool
http://romannurik.github.io/AndroidAssetStudio/ 4 - 90 4 - 91

Appendix B. DroidDraw Appendix C.


Android Asset Studio
A simple (but aging) GUI generator
LINK: www.droidDraw.org

LINK: http://romannurik.github.io/AndroidAssetStudio/ [Visited on 9/14/2014]

This tool offers a number of options to craft high-quality icons and other
displayed elements typically found in Android apps.

Icon Generators Other Generators Community Tools


Launcher icons Device frame generator Android Action Bar Style
Action bar and tab icons Generator
Notification icons Simple nine-patch gen.
Navigation drawer Android Holo Colors
indicator Generator
Generic icons

4 - 92 4 - 93
Appendix D. Measuring Graphic Elements Appendix D. Measuring Graphic Elements
How Android deals with screen resolutions?
Q. What is dpi (also know as dp and ppi) ? Illustration of how the Android platform maps actual screen densities and
Stands for dots per inch. It suggests a measure of screen quality. sizes to generalized density and size configurations.
You can compute it using the following formula:
A set of four generalized screen sizes
xlarge screens are at least 960dp x 720dp
dpi = widthPixels + heightPixels / diagonalInches
dpi = sqrt (width_pixels^2
2 + height_pixels^2)
2 / diagonal_inches
large screens are at least 640dp x 480dp A set of six generalized densities:
normal screens are at least 470dp x 320dp ldpi ~120dpi (low)
small screens are at least 426dp x 320dp mdpi ~160dpi (medium)
G1 (base device 320x480) 155.92 dpi (3.7 in diagonally) hdpi ~240dpi (high)
Nexus (480x800) 252.15 dpi xhdpi ~320dpi (extra-high)
HTC One (1080x1920) 468 dpi (4.7 in) xxhdpi ~480dpi (extra-extra-high)
Samsung S4 (1080x1920) 441 dpi (5.5 in) Xxxhdpi ~640dpi (extra-extra-extra-high)

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


dp 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
on a 160 dpi screen. Use it for measuring anything but fonts.

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

4 - 94 4 - 95
Taken from: http://developer.android.com/guide/practices/screens_support.html

Appendix D. Measuring Graphic Elements Appendix E. Hierarchy Viewer Tool


Q. Give me an example on how to use dp units. The HierarchyViewer Tool allows exploration of a
Assume you design your interface for a G1 phone having 320x480 pixels (Abstracted density is displayed UI. Use DDMS > Click on Devices > Click on
160 – See your AVD entry, the actual pixeling is defined as: [2*160] x [3*160] ) HierarchyViewer icon (next to camera)
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 ].

The XML would be

<Button
android:id="@+id/button1"
android:layout_height="wrap_content" 180 120 180

android:layout_width="120dp"
android:layout_gravity="center"
480
android:text="@+id/go_caption" />

If the application is deployed on devices having a higher resolution the button is still
mapped to the middle of the screen.

4 - 96 4 - 97
Appendix F. Customizing Widgets Appendix F. Customizing Widgets
1. The appearance of a widget can be adjusted The image shows visual feedback provided to the user during the clicking of a standard
by the user. For example a button widget and a custom Button widget. Assume the device runs under SDK4.3.
could be modified by changing its shape,
border, color, margins, etc.

2. Basic shapes include: rectangle, oval, line, and Standard


ring. behavior –
buttons turns
3. In addition to visual changes, the widget’s blue when it is
reaction to user interaction could be adjusted pressed.
for events such as: Focused, Clicked, etc.

4. The figure shows and EditText and Button


widgets as normally displayed by a device
running SDK4.3 (Ice Cream). The bottom two
widgets (a TextView and a Button) are custom
made versions of those two controls
respectively.

Custom behavior – buttons turns dark grey with


an orange border when it is pressed.
4 - 98 4 - 99

Appendix F. Customizing Widgets Appendix F. Customizing Widgets


Observe the transient response of the standard and custom made EditText When the user taps on the custom made EditText box a gradient is applied to
boxes when the user touches the widgets provoking the ‘Focused’ event. the box to flash a visual feedback reassuring the user of her selection.

When focused
the standard box
shows a blue
bottom line

A focused
custom box
shows an orange
all-around frame

1. Non-focused custom
EditText widget, grey 3. Focused custom
border EditText widget showing
an orange border

2. Clicked EditText widget


showing a yellow colored
linear gradient and orange
4 - 100 border 4 - 101
Appendix F. Customizing Widgets Appendix F. Customizing Widgets
Organizing the application Activity Layout 1 of 2
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp" >

<EditText
Definition of the custom templates for android:id="@+id/editText1"
Button and EditText widgets android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:ems="10"
android:inputType="text"
android:text="@string/standard_edittext" >
Layout referencing standard and custom <requestFocus />
made widgets </EditText>

<Button
android:id="@+id/button1"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:text="@string/standard_button" />

4 - 102 4 - 103

Appendix F. Customizing Widgets Appendix F. Customizing Widgets


Resource: res/drawable/custom_button.xml
Activity Layout (2 of 2) and Resource: res/values/strings
The custom Button widget has two faces based on the event state_pressed
<EditText (true, false). The Shape attribute specifies its solid color, padding, border
android:id="@+id/editText2"
android:layout_width="match_parent" (stroke) and corners (rounded corners have radius > 0 )
android:layout_height="wrap_content"
android:layout_marginBottom="5dp" <?xml version="1.0" encoding="utf-8"?>
android:background="@drawable/custom_edittext" <selector xmlns:android="http://schemas.android.com/apk/res/android" >
android:ems="10" <item android:state_pressed="true">
android:inputType="text" <shape android:shape="rectangle">
android:text="@string/custom_edittext" /> <corners android:radius="10dp"/>
<solid android:color="#ffc0c0c0" />
<Button <padding android:left="10dp"
android:id="@+id/button2" android:top="10dp"
android:layout_width="120dp" android:right="10dp"
android:layout_height="wrap_content" android:bottom="10dp"/>
android:background="@drawable/custom_button" <stroke android:width="1dp" android:color="#ffFF6600"/>
android:text="@string/custom_button" /> </shape>
</item>
</LinearLayout> <item android:state_pressed="false">
<shape android:shape="rectangle">
<corners android:radius="10dp"/>
<?xml version="1.0" encoding="utf-8"?> <solid android:color="#ffE0E6FF"/>
<resources> <padding android:left="10dp"
<string name="app_name">GuiDemo</string> android:top="10dp"
<string name="action_settings">Settings</string> android:right="10dp"
<string name="standard_button">Standard Button</string> android:bottom="10dp"/>
<string name="standard_edittext">Standard EditText Box</string> <stroke android:width="2dp" android:color="#ff777B88"/>
<string name="custom_button">Custom Button</string> </shape>
<string name="custom_edittext">Custom EditText Box</string> </item>
</resources> 4 - 104 </selector> 4 - 105
Appendix F. Customizing Widgets Appendix F. Customizing Widgets
Resource: res/drawable/custom_edittext.xml Resource: res/drawable/custom_edittext.xml
The rendition of the custom made EditText widget is based on three states: The rendition of the custom made EditText widget is based on three states:
normal, state_focused, state_pressed. normal, state focused, state_pressed.
<item android:state_focused="true">
<?xml version="1.0" encoding="utf-8"?> <shape>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#FFffffff" />
<stroke android:width="2dp" android:color="#FFff6600" />
<item android:state_pressed="true"> <corners android:radius="0dp" />
<shape android:shape="rectangle"> <padding android:left="10dp"
<gradient android:top="6dp"
android:angle="90" android:right="10dp"
android:centerColor="#FFffffff" android:bottom="6dp" />
android:endColor="#FFffcc00" </shape>
android:startColor="#FFffffff" </item>
android:type="linear" />
<item>
<stroke android:width="2dp" <!-- state: "normal" not-pressed & not-focused -->
android:color="#FFff6600" /> <shape>
<corners android:radius="0dp" /> <stroke android:width="1dp" android:color="#ff777777" />
<padding android:left="10dp" <solid android:color="#ffffffff" />
android:top="6dp" <corners android:radius="0dp" />
android:right="10dp" <padding android:left="10dp"
android:bottom="6dp" /> android:top="6dp"
</shape> android:right="10dp"
</item> android:bottom="6dp" />
</shape>
</item>
</selector>
4 - 106 4 - 107

Appendix G: Fixing Bleeding Background Color Appendix H: Useful Color Theme (Android Holo)
You may change a layout’s color by simply adding in the XML layout the clause
android:background="#44ff0000" (color is set to semi-transparent red). The screen shows color included in Android’s Holo-Theme. The Holo-Theme
color set provides a palette of harmonious colors recommended for all your
The problem is that the layout color appears to be placed on top of the other controls
making them look ‘smeared’ as show in the figure below (right). applications.
Benefits: uniform design, homogeneous
Although tedious, a solution is to reassert the smeared widgets’ appearance by user-experience, beauty(?)…
explicitly setting a value in their corresponding android:background XML attributes.
The figure on the left includes explicit assignments to the widgets’ background. You may want to add the following entries to your
res/values/colors.xml file. Example of usage:
android:background="@color/holo_blue_light"

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


<resources>
1
<color name="holo_blue_light">#ff33b5e5</color>
<color name="holo_blue_dark">#ff0099cc</color>
2 <color name="holo_blue_bright">#ff00ddff</color>
<color name="gray_light">#fff0f0f0</color>
<color name="gray_dark">#ff313131</color>
3 <color name="gray_bright">#ffd0d0d0</color>

</resources>
1. android:background="@android:drawable/edit_text"
2. android:background="@android:drawable/editbox_dropdown_light_frame"
3. android:background="@android:drawable/btn_default" For a long list of HEX colors to be copied in your res/values/colors.xml resource file
4 - 108
see http://stackoverflow.com/questions/3769762/android-color-xml-resource-file

You might also like