Packt Publishing Android User Interface Development, Beginner's Guide (2011)

User Manual: Pdf

Open the PDF directly: View PDF PDF.
Page Count: 304

DownloadPackt Publishing Android User Interface Development, Beginner's Guide (2011)
Open PDF In BrowserView PDF
Download from Wow! eBook 

Android User Interface
Development
Beginner's Guide

Quickly design and develop compelling user interfaces for
your Android applications

Jason Morris

BIRMINGHAM - MUMBAI

Android User Interface Development
Beginner's Guide

Copyright © 2011 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system,
or transmitted in any form or by any means, without the prior written permission of the
publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals. However,
Packt Publishing cannot guarantee the accuracy of this information.

First published: February 2011
Production Reference: 1160211

Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-849514-48-4
www.packtpub.com

Cover Image by Charwak A (charwak86@gmail.com)

Credits
Author
Jason Morris
Reviewers
David J. Groom
Martin Skans
Acquisition Editor
Chaitanya Apte
Development Editor
Reshma Sundaresan
Technical Editor
Harshit Shah
Copy Editor
Neha Shetty
Indexer
Tejal Daruwale

Editorial Team Leader
Akshara Aware
Project Team Leader
Priya Mukherji
Project Coordinator
Shubhanjan Chatterjee
Proofreader
Joel T. Johnson
Graphics
Nilesh R. Mohite
Production Coordinators
Kruthika Bangera
Aparna Bhagat
Cover Work
Kruthika Bangera

About the Author
Jason Morris has worked on software as diverse as fruit tracking systems, insurance
systems, and travel search and booking engines. He has been writing software for as long
as he can remember. He is currently working as a Software Architect for Travelstart in South
Africa. He works on multiple front-end and middleware systems, leveraging a variety of Java
based technologies.
The people I'd like to thank most for their direct, or indirect help in writing
this book are my wife Caron Morris, my father Mike Morris, my mom Jayne
Morris, and the rest of my family for their love and support. I'd also like
to thank Wayne, Stuart, Angela, and James, and everyone on my team at
Travelstart. Finally a very big thanks to Martin Skans for his invaluable input.

About the Reviewer
Martin Skans graduated from Lund University in Sweden, with a Master's degree in
Computer Science. After a couple of years in the online marketing industry, he moved on to
become a developer for Travelstart, an online travel agency. He relocated to Cape Town and
is currently working on Travelstart's African travel platform which has been recently launched
for the mobile market.

www.PacktPub.com
Support files, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support files and downloads related to your
book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub
files available? You can upgrade to the eBook version at www.PacktPub.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
service@packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a
range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book
library. Here, you can access, read and search across Packt's entire library of books.

Why Subscribe?
‹‹

Fully searchable across every book published by Packt

‹‹

Copy and paste, print and bookmark content

‹‹

On demand and accessible via web browser

Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view nine entirely free books. Simply use your login credentials for
immediate access.

Table of Contents
Preface
Chapter 1: Developing a Simple Activity
Developing our first example
Creating the project structure
Time for action – setting up the Android SDK
Time for action – starting a new project
Examining the Android project layout
Time for action – running the example project
The screen layout
The layout XML file
Resource selection qualifiers

Time for action – setting up the question activity
Populating a View and a ViewGroup
Time for action – asking a question
Time for action – adding a space for answers
Time for action – adding more buttons
Defining common dimensions
Limitations of the layout XML format
Populating the QuestionActivity
Time for action – writing more Java code
Dynamically creating widgets
Time for action – putting the questions on the screen
Handling events in Android
Summary

Chapter 2: Presenting Data for Views
Listing and selecting data
ListView choice modes
No selection mode – CHOICE_MODE_NONE
Single selection mode – CHOICE_MODE_SINGLE
Multiple selection mode – CHOICE_MODE_MULTIPLE

1
11
11
12
12
13
14
14
15
16
16

18
19
19
21
23
25
27
29
30
32
32
34
36

37
38
38
38
39
40

Table of Contents

Adding header and footer widgets
Creating a simple ListView
Time for action – creating a fast food menu
Styling the standard ListAdapters
Defining standard dimensions

40
41
41
43
43

Time for action – improving the restaurant list
Creating custom adapters
Creating a menu for The Burger Place

44
47
47

Time for action – creating a Burger item layout
Time for action – presenting Burger objects
Creating TheBurgerPlaceActivity class
Time for action – implementing TheBurgerPlaceActivity
Registering and starting TheBurgerPlaceActivity
Using the ExpandableListView class
Creating ExpandableListAdapter implementations
Using the GridView class
Time for action – creating the fruit icon
Displaying icons in a GridView
Time for action – building the fruit menu
Time for action – creating the FourBucketsActivity
Summary

Chapter 3: Developing with Specialized Android Widgets
Creating a restaurant review application
Time for action – creating the robotic review project structure
Building a TabActivity
Creating tab icons
Android tabs and icons
Implementing the ReviewActivity
Time for action – writing the ReviewActivity class
Time for action – creating the Review layout
Working with switcher classes
Time for action – turning on the TextSwitcher
Creating a simple photo gallery
Time for action – building the Photos tab
Creating a thumbnail widget
Implementing a GalleryAdapter
Time for action – the GalleryAdapter
Time for action – making the gallery work
Building the reservation tab
Time for action – implementing the reservation layout
Time for action – initializing the reservation tab
[ ii ]

48
50
52
53
54
56
57
58
59
60
61
62
64

67
68
68
70
70
71
72
72
74
75
76
78
79
80
80
81
83
86
86
89

Table of Contents

Time for action – listening to the SeekBar
Time for action – selecting date and time
Creating complex layouts with Include, Merge, and ViewStubs
Using Include tags
Merging layouts
Using the ViewStub class
Summary

Chapter 4: Leveraging Activities and Intents
Exploring the Activity class
Using Bundle objects
Time for action – building an example game: "guess my number"
Creating and consuming intents
Defining Intent actions
Passing data in an Intent
Adding extra data to an Intent
Using advanced Intent features
Getting data back from an Intent
Time for action – viewing phone book contacts
Summary

Chapter 5: Developing Non-linear Layouts
Time for action – creating a layouts example project
FrameLayout
Common uses
Time for action – developing a FrameLayout example
Table Layout
Common uses
Using TableLayout for a memory game
Time for action – developing a simple memory game
AbsoluteLayout/Custom Layouts
Developing your own Layouts
Time for action – creating a custom layout
Using the CircleLayout
Time for action – finishing the CircleLayout example
RelativeLayout
Common uses
Integrating the RelativeLayout
Time for action – creating a contact editor
Time for action – integration with the layout example
SlidingDrawer
Common uses
[ iii ]

92
93
96
97
97
99
100

103
104
105
106
110
111
112
112
113
113
114
118

119
120
121
121
122
126
127
127
128
133
134
134
137
137
140
140
141
141
144
146
146

Table of Contents

Creating a SlidingDrawer example
Time for action – creating a SlidingDrawer
Time for action – sliding drawer integration
Summary

Chapter 6: Validating and Handling Input Data
Dealing with undesirable input
Correctly labeling input
Signaling undesirable input
Recovering from undesirable input
Giving users direct feedback
Avoiding invalid input entirely
Capturing date and time
Using spinners and ListView for selection
Changing the data set
Disabling selections

147
147
148
150

153
153
154
154
155
155
156
156
159
159
159

Capturing text input
Autocompleting text input
Building activities for results
Generic filtering search Activity
Time for action – creating the ListItemSelectionActivity
Time for action – creating an ArrayAdapter
Time for action – creating the CursorAdapter
Time for action – setting up the ListView
Time for action – filtering the list
Time for action – returning the selection
Using the ListItemSelectionActivity
Summary

Chapter 7: Animating Widgets and Layouts
Using standard Android animations
Time for action – animating a news feed
Using flipper and switcher widgets
Using the ImageSwitcher and TextSwitcher implementations
Animating layout widgets
Time for action – animating a GridView
Creating Custom Animations
Time for action – writing a custom animation
Time for action – making a Button vanish
Summary

Chapter 8: Designing Content-centric Activities
Considering design options when displaying content on an Android device
[ iv ]

160
160
162
162
163
164
165
169
170
171
172
174

175
176
176
181
182
182
183
187
188
189
192

193
194

Download from Wow! eBook 

Table of Contents

Considering user behavior

195

Drawing user attention

196

Displaying content with the WebView class
Using a WebView object
Time for action – creating a recipe viewer application
Taking WebView further
Creating relative layouts for content display
Taking full advantage of RelativeLayout
Considering Android layout constraints
Styling TextView objects
Time for action – developing specialized content views
Developing an online music store
Designing the music store
Developing the music store
Time for action – building a track item
Time for action – developing the main user interface layout
Time for action – developing the main user interface Java code
Summary

Chapter 9: Styling Android Applications
Working with style resources
Using shape resources
How shapes behave

197
198
198
203
204
205
206
207
210
213
213
215
218
219
222
225

227
228
230
231

Rendering lines

231

Time for action – drawing a broken line
Rendering rectangles
Time for action – creating a rounded border
Rendering ovals
Time for action – applying a gradient to an oval shape
Rendering rings
Time for action – rendering a spinner ring
Defining layers
Stretching using nine-patch images
Creating nine-patch images
Using bitmap images in Android
Handling different screen sizes
Handling different screen densities
Handling configuration changes
Providing landscape layouts
Providing text input on a landscape layout
Altering screen content
Summary
[v]

231
232
232
234
235
236
237
238
239
240
241
242
243
244
245
246
247
247

Table of Contents

Chapter 10: Building an Application Theme
Creating a basic calculator layout
Designing a standard calculator
Time for action – building the standard calculator
Building the calculator styling
Time for action – creating the button images
Time for action – styling the calculator buttons
Time for action – styling the display
Scientific landscape layout
Defining string resources for the scientific layout
Styling the scientific layout
Building the scientific layout
Time for action – coding the scientific layout
Handling the Activity restart
Supporting hardware keyboards
Adding in display animations
Time for action – animating the display
Summary

Appendix: Pop quiz answers

249
250
251
252
254
255
257
260
263
263
265
265
266
269
270
271
271
274

275

Chapter 1
Layouts as XML fles
Populating an activity
Chapter 2
List views and adapters
Chapter 3
Gallery objects and ImageViews
Chapter 4
Intents & Activities
Chapter 5.
Custom layouts
Chapter 6
Text input
Chapter 8
The WebView widget
WebView versus native layouts
Chapter 10
Layout resources
Nine-Patch Images
Android resources

275
275
275
276
276
276
276
276
276
277
277
277
277
277
277
277
278
278
278
278

Index

279
[ vi ]

Preface
On 9th January, 2007, Apple officially launched the iPhone, and the world of user interface
design shifted. While tablet PCs had been around for a while, the iPhone was the first device
to give so many people a portable touchscreen, and people loved it. Just over a year later,
Google and the Open Handset Alliance announced Android which in many ways is the direct
competitor to iPhone.
What is it about touchscreen phones that we love? The answer is simple—feedback.
Touchscreens offer a way to directly manipulate on-screen objects, which in the past had to
be driven through a keyboard, mouse, joystick, or other input device. The touchscreen model
of direct manipulation has a large impact on the way we think about our user interfaces as
developers, and changes the expectations a user has for the application. Touchscreen devices
require us to stop thinking in terms of forms, and start thinking about object-oriented user
interfaces.
Android is used as the primary operating system for a rapidly expanding range of consumer
electronics, including:
‹‹

Smartphones

‹‹

Netbooks

‹‹

Tablets

‹‹

Some desktop systems

While all of these devices have different purposes and specifications, all of them run
Android. This is unlike many other operating environments which are almost always have a
special purpose. The services and the APIs they provide to developers generally reflect their
target hardware. Android on the other hand makes the assumption that a single application
may be required to run on many different types of devices, with very different hardware
capabilities and specifications, and makes it as easy as possible for developers to handle the
differences between these devices simply and elegantly.

Preface

New challenges

As Android and the touchscreen devices it powers become increasingly common, they will
bring a new set of challenges to user interface design and development:
‹‹

You generally don't have a mouse

‹‹

You may have more than one pointing device

‹‹

You often don't have a keyboard

‹‹

Any keyboard that does exist may be a software keyboard

‹‹

A software keyboard may consume some of your application's screenspace

The software keyboard reduces the amount of screen space available to your application,
and in much the same vein, if there is a hardware keyboard present it may or may not always
be exposed to the user. Therefore, not only are different Android devices different, but they
may also appear to change features while your application is running.

The rule of finger
Most Android devices have touchscreens (although this is not a requirement). The first
restriction placed on any touchscreen user interface is the size of the human forefinger,
which of course varies widely from one person to another. If a widget is too small on the
screen, it won't be clear what the user is trying to touch. You'll notice that most Android
widgets take up plenty of space, and have more than the normal amount of padding around
them. On a touchscreen device, you can't rely on pixel-perfect precision. You need to make
sure that when the user touches a widget, they make contact, and they don't accidentally
touch another widget.

The magic touch
Another impact touchscreens have on user interface design is that an application and all the
widgets that it uses must be entirely self-explanatory (even more than usual). Far too often,
we substitute good user interface planning and design with a roll-over or tooltip to indicate
a widget's function. On a touchscreen device, there is no mouse or pointing device. The first
interaction it has with the user is when they touch it, and they will expect something to happen.
A touchy subject
Most Android devices have a touchscreen, but it's not a requirement. The quality of
a touchscreen also varies wildly from device to device. The category of touchscreens
and their capabilities will also vary from one device to the next, depending on the
intended use of the device and often its intended market segment.

[2]

Preface

A smaller view on the world
Most Android devices are small, and as a result have smaller screens and generally fewer
pixels than a normal PC or laptop. This lack of size limits the size of the widgets. Widgets
must be big enough to touch safely, but we also need to pack as much information onto the
screen as possible. So don't give your users information that they don't want, and also avoid
asking them for information you don't need.

Classic user interface principals

Here are some core guidelines which every user interface should follow. These guidelines
are what will keep your users happy, and ensure your application is successful. Throughout
the rest of the book, we'll be walking through these guidelines with practical examples of
improvements that can be made to a user interface.

Consistency
This is the cornerstone of good user interface design. A button should look like a button.
Make sure that the layout of each screen has a relationship with every other screen in your
application. People often mistake this principle for "stick to the platform look and feel". Look
and feel is important, consistency mostly applies to the layout and overall experience of the
application, rather than the color scheme.

Recycling your interface
The easiest way to maintain a consistent user interface, is to recycle as much of it as possible.
At first glance, this suggestion looks merely like a "good object-oriented" practice. However,
a closer look will reveal ways to reuse graphical widgets in ways you hadn't thought of. By
changing the visibility of various widgets, or you can reuse an edit screen to view list items
of the intended type.

Simplicity
This is especially important in a phone-based application. Often, when a user encounters a
new application, it's because they are looking for something. They may not have the time
(or more often patience) to learn a new user interface. Make sure that your application
asks for as little as possible, and guides the user to the exact information they want in as
few steps as possible.

[3]

Preface

The Zen approach
Generally, when you are using a mobile device, your time is limited. You may also be using
an application in less-than-ideal circumstances (perhaps, in a train). The lesser information
a user needs to give an application, and the lesser they need to absorb from it, the better.
Stripping away options and information also leads to a shorter learning-curve.

Android's hidden menu
A very useful feature of Android is the hidden menu structure. The menu is only visible
when the user presses the "Menu" button, which would generally mean, they're looking
for something that isn't currently on the screen. Typically, a user shouldn't need to open a
menu. However, it's a good way of hiding advanced features until they are needed.

Feedback
Feedback is what makes a touchscreen device exciting. When you drag an object, it sticks to
your finger across the screen until you let go of it. When the users puts their finger on your
application, they expect some reaction. However, you don't want to get in their way—instead
of showing an error message when they touch a button, disable the button until it's valid to
use, or don't show it at all.

Location and navigation
When you're in a place you've never been to previously, it's easy to get disoriented, or lost.
The same is true for a piece of software. Just because the application makes sense to you,
the developer, it doesn't mean it seems logical to your user. Adding transition animations,
breadcrumbs, and progress gauges help the user to identify where in the application they
are, and what's happening.

The road to recovery
A common way to tell users that something is wrong on a desktop application, or on the web
is to open an error dialog. On a mobile device, people want smoother use of an application.
While in a normal application you may inform the user that they selected an invalid option,
in a mobile application, you generally want to make sure they can't select that option in the
first place. Also, don't make them scroll through huge lists of options. Instead, allow them to
filter through the list using an auto-complete or something similar.
When something goes wrong, be nice, and be helpful—don't tell the user, "I couldn't find any
flights for your search". Instead tell them, "There were no available flights for your search,
but if you're prepared to leave a day earlier, here is a list of the available flights". Always
make sure your user can take another step forward without having to go "Back" (although
the option to go backwards should always exist).
[4]

Preface

The Android way

The Android platform is in many ways similar to developing applications for the web.
There are many devices, made by many manufactures, with different capabilities and
specifications. Yet as a developer, you will want your users to have the most consistent
experience possible. Unlike a web browser, Android has built-in mechanisms for coping with
these differences, and even leveraging them.
We'll be looking at Android from the point of view of a user rather than having a purely
development-centric approach. We'll cover topics such as:
‹‹

What user interface elements Android provides

‹‹

How an Android application is assembled

‹‹

Different types of Android layouts

‹‹

Presenting various types of data to the user

‹‹

Customising of existing Android widgets

‹‹

Tricks and tools to keep user interfaces looking great

‹‹

Integration between applications

We're about to take a jump into building user interfaces for Android devices—all Android
devices, from the highest speed CPU to the smallest screen.

What this book covers

Chapter 1, Developing a Simple Activity introduces the basics of building an Android
application, starting with a simple user interface. It also covers the various options available
to you when implementing your design as code.
Chapter 2, Views With Adapters shows us how to leverage Adapter-based widgets, Android's
answer to the Model-View-Controller (MVC) structure. Learn about these widgets, and
where they will best serve you.
Chapter 3, Specialized Android Views takes a close look at some of the more specialized
widgets that the Android platform provides, and how they relate to the mundane widgets.
This chapter covers widgets such as the gallery and rating-bar, and how they can be used and
styled.
Chapter 4, Activities and Intents discusses more about how Android runs your application,
and from that point-of-view, how best to write its user interfaces. This chapter takes a look at
how to make sure that your application will behave the way users expect it to, with minimal
effort on your part.

[5]

Preface

Chapter 5, Non-Linear Layouts takes a look at some of the advanced layout techniques which
Android offers. It talks about the best way to present different screens to the user while
taking into account the wide discrepancy in the screens on Android devices.
Chapter 6, Input and Validation provides tips regarding taking input from a user, and how
to keep this experience as painless as possible. This chapter investigates the different input
widgets Android provides and how to configure them best, depending on the situation. Also,
when everything else fails, how best to inform your users that what they are doing is wrong.
Chapter 7, Animating Widgets and Layouts will inform the reader as to where, when,
why, and how to animate your Android user interfaces. It also sheds light on what kind of
animations are provided by default, how to compose them together, and how to build your
own. This chapter looks at the importance of animations in a mobile user interface and
demonstrates how complex animations are made easy by Android.
Chapter 8, Content-centric Design details how to go about designing the screen layout, when
presenting the user with information on the screen. This chapter looks at the pros and cons
of some of the different display techniques which Android offers.
Chapter 9, Styling Android Applications shows us how to keep the look of our entire
application consistent, in order to make our application easier to use.
Chapter 10, Building an Application Theme looks at the design process, and how applicationwide themes can be applied to help your application stand out.

What you need for this book

Please have a look at "System Requirements" mentioned on the Andriod Developers website
at http://developer.android.com/sdk/requirements.html.
The code for this book was tested on Ubuntu Linux 10.04 and Mac OS X.

Who this book is for

This book is aimed at developers with at least some Java experience who want to build
applications on the Android platform. It will also be of use to people who have developed
applications on the Android platform and would like to gain additional knowledge about
its user interface design. It will also be a helpful reference for the numerous widgets and
resource structures that the Android platform provides.

[6]

Preface

This book will also be helpful to:
‹‹

Java developers learning Android development

‹‹

MIDP developers looking to broaden their skill-set

‹‹

iPhone developers wanting to port applications

‹‹

Entrepreneurial Android developers wanting to widen their user base

Conventions

In this book, you will find several headings appearing frequently.
To give clear instructions of how to complete a procedure or task, we use:

Time for action – heading
1.

Open the res/layout/main.xml layout resource in an editor or IDE.

2.

Remove the default content within the LinearLayout element.

Instructions often need some extra explanation so that they make sense, so they are
followed with:

What just happened?
This heading explains the working of tasks or instructions that you have just completed.
You will also find some other learning aids in the book, including:

Pop quiz – heading
These are short multiple choice questions intended to help you test your own understanding.

Have a go hero – heading
These set practical challenges and give you ideas for experimenting with what you have learned.
You will also find a number of styles of text that distinguish between different kinds of
information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: "We'll start off by creating a selector Activity,
and a simple NewsFeedActivity".

[7]

Preface

A block of code is set as follows:







When we wish to draw your attention to a particular part of a code block, the relevant lines
or items are set in bold:







Any command-line input or output is written as follows:
android create project -n AnimationExamples -p AnimationExamples -k com.
packtpub.animations -a AnimationSelector -t 3

New terms and important words are shown in bold. Words that you see on the screen, in
menus or dialog boxes for example, appear in the text like this: "Generally users are more
inclined to feel a sense of trust if they pick the Buy Music button and are not suddenly
whisked off to their web browser".
Warnings or important notes appear in a box like this.

[8]

Preface

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this
book—what you liked or may have disliked. Reader feedback is important for us to
develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to feedback@packtpub.com, and
mention the book title via the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in the
SUGGEST A TITLE form on www.packtpub.com or e-mail suggest@packtpub.com.
If there is a topic that you have expertise in and you are interested in either writing or
contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you
to get the most from your purchase.
Downloading the example code for this book
You can download the example code files for all Packt books you have purchased
from your account at http://www.PacktPub.com. If you purchased this
book elsewhere, you can visit http://www.PacktPub.com/support and
register to have the files e-mailed directly to you.

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you find a mistake in one of our books—maybe a mistake in the text or the
code—we would be grateful if you would report this to us. By doing so, you can save other
readers from frustration and help us improve subsequent versions of this book. If you
find any errata, please report them by visiting http://www.packtpub.com/support,
selecting your book, clicking on the errata submission form link, and entering the details
of your errata. Once your errata are verified, your submission will be accepted and the
errata will be uploaded on our website, or added to any list of existing errata, under the
Errata section of that title. Any existing errata can be viewed by selecting your title from
http://www.packtpub.com/support.
[9]

Preface

Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt,
we take the protection of our copyright and licenses very seriously. If you come across any
illegal copies of our works, in any form, on the Internet, please provide us with the location
address or website name immediately so that we can pursue a remedy.
Please contact us at copyright@packtpub.com with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions
You can contact us at questions@packtpub.com if you are having a problem with any
aspect of the book, and we will do our best to address it.

[ 10 ]

1

Developing a Simple Activity
In the world of Android, an Activity is the point at which you make contact
with your users. It's a screen where you capture and present information to the
user. You can construct your Activity screens by using either: XML layout files
or hard-coded Java.

To begin our tour of Android user interfaces, we need a user interface to start with. In this
chapter, we will begin with a simple Activity. We will:
‹‹

Create a new Android project

‹‹

Build the Activity layout in an application resource file

‹‹

Tie the resource file to an Activity class

‹‹

Dynamically populate the Activity with a series of multiple-choice questions

Developing our first example
For our first example, we're going to write a multiple-choice question and answer Activity.
We could use it for applications such as "Who wants to be a millionaire?", or "What type of
a monkey are you?". This example will pose questions in order to answer a very important
question: "What should I have to eat?" As the user answers the questions, this application
will filter a database of food ideas. The user can exit the process at any time to view a list of
suggested meals, or just wait until the application runs out of questions to ask them.
Since it's a user interface example, we'll skip building filters and recipe databases. We'll just
ask our user food preference-related questions. For each question, we have a list of preset
answers which the user can select from (that is, multiple-choice questions). Each answer
they give will allow us to narrow the list of suitable recipes.

Developing a Simple Activity

Creating the project structure
Before we can start writing code, we need a project structure. An Android project
is made up of far more than just its Java code—there are also manifest files, resources,
icons, and more. In order to keep things easy, we use the default Android toolset
and project structure.
You can download the latest version of the Android SDK for your favorite operating system from
http://developer.android.com. A single Android SDK may be used to develop against any
number of target Android versions. You will need to follow the installation instructions on the
website at http://developer.android.com/sdk/installing.html to install the latest
SDK "starter package" and one or more platform targets. Most of the examples in this book will
work on Android 1.5 and higher. The Android website also maintains a very useful chart where
you can see what the most popular versions of Android are.

Time for action – setting up the Android SDK
Once you have downloaded the Android SDK archive for your operating system, you'll need
to install it and then download at least one Android Platform package. Open a command-line
or console and complete the following steps:

1.

Extract the Android SDK archive.

2.

Change directory to the root of the unpackaged Android SDK.

3.

Change directory to the tools directory of the Android SDK.

4.

Update the SDK by running the following command:
android update sdk

5.

Create a new Virtual Device by going to the Virtual Devices screen and clicking on
the New button. Name the new Virtual Device default.

6.

Specify its target as the most recent version of Android downloaded by the SDK. Set
the size of the SD Card to 4096 MiB. Click on the Create AVD button.

What just happened?
The above command tells the new Android SDK installation to look for available packages
and install them. This includes installing a Platform Package. Each Platform Package that you
install can be used to create an Android Virtual Device (AVD). Each AVD you create is much
like buying a new device on which tests can be performed, each with its own configuration
and data. These are virtual machines that the Android emulator will run your software on
when you wish to test.
[ 12 ]

Download from Wow! eBook 

Chapter 1

Time for action – starting a new project
The Android SDK provides a handy command-line tool named android which can be used
to generate the skeleton of a new project. You'll find it under the tools directory of your
Android SDK. It's capable of creating a basic directory structure and a build.xml file (for
Apache Ant) to help get you started with your Android application development. You will
need to make sure that the tools directory is in your executable path for this to work. Open
a command-line or console.

1.

Create a new directory in your home directory or desktop named
AndroidUIExamples. You should use this directory for each of the examples
in this book.

2.

Change the directory to the new AndroidUIExamples.

3.

Run the following command:
android create project -n KitchenDroid -p KitchenDroid -k com.packtpub.
kitchendroid -a QuestionActivity -t 3

What just happened
We just created a skeleton project. In the preceding command line, we used the following
options to specify the structure of the new project:
Option
-n

Description

-p

Gives the base directory for the project. In this case use the same name as that of the
project. The android tool will create this directory for you.

-k

Specifies the root Java package for the application. This is a fairly important concept
since it defines our unique namespace on the Android client devices.

-a

Gives the tool a name for a "main" Activity class. This class will be populated
with a skeleton layout XML, and serves as a base point to build your application from.
The skeleton project will be pre-configured to load this Activity when it's started.

Gives the project a name, in our case, KitchenDroid. This is really just an internal
identifier for the project.

If you run the command android list targets and it presents you with an empty list of
possible targets, then you have not downloaded any of the Android Platform packages. You
can generally run the android tool by itself and use its graphical interface to download and
install Android Platform packages. The previous example uses API Level 3 which corresponds
to Android Platform version 1.5.

[ 13 ]

Developing a Simple Activity

Examining the Android project layout
A typical Android project has almost as many directories and files as an enterprise Java
project. Android is as much of a framework as it is an operating environment. In some ways,
you can think of Android as an application container designed for running on phones and
other limited devices.
As part of the new project structure, you will have the following important files and directories:
Folder name
bin
gen
res
src
AndroidManifest.xml

Description
Your binary files will be placed in this directory by the compiler.
Source code generated by various Android tools.
Application resources go here, to be compiled and packaged with
your application.
The default Java source code directory, where the build script
will look for source code to compile.
Your application descriptor, similar to a web.xml file.

Resource Types and Files
Most types of application resources (placed in the res directory) receive special
handling by the Android application packager. This means these files consume
less space than they usually would (since XML is compiled into a binary format
instead of being left as plain text). You access resources in various ways, but
always through an Android API (which decodes them into their original form for
you).
Each subdirectory of res indicates a different file format. Therefore, you cannot
put files directly into the root res directory since the package tool won't know
how to handle it (and you'll get a compile error). If you need to access a file in its
raw state, put it in the res/raw directory. Files in the raw directory are copied
byte-for-byte into your application package.

Time for action – running the example project
The android tool has given us a minimal example of an Android project, basically a "Hello
World" application.

1.

In your console or command-line, change directory to KitchenDroid.

2.

To build and sign the project, run:
ant debug

3.

You will need to start the emulator with the default AVD you created earlier:
emulator -avd default
[ 14 ]

Chapter 1

4.

Now install your application in the emulator:
ant install

5.

In the emulator, open the Android menu and, you should see an icon named
QuestionActivity in the menu. Click on this icon.

What just happened?
The Android emulator is a full hardware emulator including the ARM CPU, hosting the entire
Android operating system stack. This means software running under the emulator will run
exactly how it will on bare-metal hardware (although the speed may vary).
When you use Ant to deploy your Android applications, you will need to use the install
Ant target. The install Ant target looks for a running emulator and then installs the
application archive on its virtual memory. It's useful to note that Ant will not start the
emulator for you. Instead, it will emit an error and the build will fail.
Application Signatures
Every Android application package is digitally signed. The signature is used to
identify you as a developer of the application, and establish permissions for the
application. It's also used to establish permissions between applications.
You will generally use a self-signed certificate, since Android doesn't require that
you use a certificate authority. However, all applications must be signed in order
for them to be run by the Android system.

The screen layout
While Android allows you to create a screen layout in either Java code, or by declaring the
layout in an XML file, we will declare the screen layout in an XML file. This is an important
decision for several reasons. The first is that, using the Android widgets in Java code requires
several lines of code for each widget (a declaration/construction line, several lines invoking
setters, and finally adding the widget to its parent), while a widget declared in XML takes up
only one XML tag.

[ 15 ]

Developing a Simple Activity

The second reason for keeping layouts as XML is that it's compacted into a special Android
XML format when it's stored in the APK file. Therefore your application uses less space on
the device, takes less time to download, and its in-memory size is also smaller since less byte
code needs to be loaded. The XML is also validated by the Android resource packing tool
during compilation, and so is subject to the same type safety as Java code.
The third reason XML layouts are a "good idea" is that they are subject to the same resource
selection process as all the other external resources. This means that a layout can be varied
based on any of the defined properties, such as language, screen orientation and size, and
even the time of day. This means that you can add new variations on the same layout in
the future, simply by adding new XML files, and without the need to change any of your
Java code.

The layout XML file
All XML layout files must be placed in the /res/layout directory of your Android
project in order for the Android packaging tools to find them. Each XML file will result
in a resource variable of the same name. For example, if we name our file /res/layout/
main.xml, then we can access it in Java as R.layout.main.
Since we are building the screen layout as a resource file, it will be loaded by the application
resource loader (having been compiled by the resource compiler). A resource is subject to a
selection process, so while there is only one resource that the application loads, there may
be multiple possible versions of the same resource available in the application package. This
selection process is also what Android internationalization is built on top of.
If we wanted to build a different version of the user interface layout for several different
types of touchscreens, Android defines three different types of touchscreen properties for
us: notouch, stylus, and finger. This roughly translates to: no touchscreen, resistive
touchscreen, and capacitive touchscreen. If we wanted to define a more keyboard-driven
user interface for devices without a touchscreen (notouch), we write a new layout XML file
named /res/layout-notouch/main.xml. When we load the resource in our Activity
code, the resource selector will pick the notouch version of the screen if the device we're
running on doesn't have a touchscreen.

Resource selection qualifiers
Here is a list of commonly used qualifiers (property names) that will be taken into account
when Android selects a resource file to load. This table is ordered by precedence, with the
most important properties at the top.

[ 16 ]

Chapter 1

Name

Description

Examples

MCC and MNC The mobile-country-code (MCC) and mobile-networkcode (MNC). These can be used to determine which
mobile operator and country the SIM card in the device is
tied to.
The mobile-network-code optionally follows the mobilecountry-code, but cannot be used on its own (you must
always specify country-code first).

API
Level

mcc505
1
mcc505-mnc03
mcc238
mcc238-mnc02
mcc238-mnc20

en
en-rUS
es
es-rCL
es-rMX

1

small
medium
large

4

Screen aspect This is the aspect type of the screen, based on the way
the device would "normally" be used. This value doesn't
change based on the orientation of the device.

long
notlong

4

Screen
orientation

Used to determine whether the device is currently in
portrait (port) or landscape (land) mode. This is only
available on devices that can detect their orientation.

land
port

1

Night mode

This value simply changes with the time of day.

night
notnight

8

Language and Language and region codes are probably the most
region codes commonly used resource properties. This is generally
how you localize your application to the user language
preferences.
These values are standard ISO language and region
codes, and are not case-sensitive. You cannot specify a
region without a country code (similar to java.util.
Locale).
Screen size

There are only three variations of this property: small,
medium, and large. The value is based on the amount of
screen space that can be used:
‹‹

Small: QVGA (320×240 pixel) low-density type
screens;

‹‹

Medium: WQVGA low-density, HVGA (480x360
pixels) medium-density, and WVGA high-density
type screens;

‹‹

Large: VGA (640x480 pixels) or WVGA mediumdensity type screens

[ 17 ]

Developing a Simple Activity

Name

Description

Screen density The DPI of the device screen. There are four possible
(DPI)
values for this property:

Keyboard
status

‹‹

ldpi: Low-density, approximately 120dpi;

‹‹

mdpi: Medium-density, approximately 160dpi;

‹‹

hdpi: High-density, approximately 240dpi;

‹‹

nodpi: Can be used for bitmap resources that
shouldn't be scaled to match the screen density

Examples

API
Level

ldpi
mdpi
hdpi
nodpi

4

keysexposed
What sort of keyboard is available on this device? This
keyshidden
attribute shouldn't be used to determine whether the
keyssoft
device has a hardware keyboard, but instead whether a
keyboard (or software keyboard) is currently visible to the
user.

1

Time for action – setting up the question activity
To kick things off we're going to be working with Android's simplest layout called:
LinearLayout. Unlike Java AWT or Swing, Android layout managers are defined as
specific container types. Thus a LinearLayout is much like a Panel with a built-in
LayoutManager. If you've worked with GWT, you'll be quite familiar with this concept. We'll
lay out the screen in a simple top-to-bottom structure (which LinearLayout is perfect for).

1.

Open the file in the /res/layout directory of your project named main.xml in
you favorite IDE or text editor.

2.

Delete any template XML code.

3.

Copy the following XML code into the file:




What just happened?
We just removed the "Hello World" example, and put in an entirely empty layout structure
which will serve as the platform for us to build the rest of the user interface upon. As you can
see, Android has a special XML namespace for its resources.
[ 18 ]

Chapter 1

All resource types in Android use the same XML namespace.

We declare our root element as LinearLayout. This element corresponds directly to
the class android.widget.LinearLayout. Each element or attribute prefixed with
the Android namespace corresponds to an attribute that is interpreted by the Android
resource compiler.
The AAPT (Android Asset Packaging Tool) will generate an R.java file into your root (or
primary) package. This file contains all of the Java variables used to reference your various
application resources. In our case, we have the main.xml package in the /res/layout
directory. This file becomes an R.layout.main variable with a constant value assigned
as its identification.

Populating a View and a ViewGroup
A widget in Android is called a View, while a container (such as LinearLayout) is a
ViewGroup. We have an empty ViewGroup now, but we need to start populating it in
order to build up our user interface. While it is possible to nest a ViewGroup inside another
ViewGroup object, an Activity has only one root View—so a layout XML file may have
only one root View.

Time for action – asking a question
In order to ask our user a question, you will need to add a TextView to the top of your
layout. A TextView is a bit like a Label or JLabel. It's also the base class for many other
Android View widgets that display text. We want it to take up all of the available horizontal
space, but only enough vertical space for our question to fit. We populate the TextView
with Please wait... as its default text. Later, on we will replace this with a dynamically
selected question.

1.

Go back to your main.xml file.

2.

Between the  and  create a  element, ending it with the empty element /> syntax since elements
representing View objects are not allowed to have child elements.

3.

Give the TextView element an ID attribute:
android:id="@+id/question"

[ 19 ]

Developing a Simple Activity

4.

Change the layout width and height attributes to fill_parent and wrap_
content respectively (the same as the LinearLayout element):
android:layout_width="fill_parent"
android:layout_height="wrap_content"

5.

Give the TextView some placeholder text so we can see it on the screen:
android:text="Please wait..."

6.

Reinstall the application using Apache Ant from your project root folder:
ant install

7.

Run the application again in the emulator and it should look like the following
screenshot:

The code for the TextView should end up looking something like this:


What just happened
In the preceding example, we used fill_parent and wrap_content as values for the layout
width and height attributes. The fill_parent value is a special value that is always equal to
the parent size. If it's used as the value for the android:layout_width attribute (as in our
example), then it's the width of the parent view. If it's used in the android:layout_height
attribute, it would be equal to the height of the parent view instead.
The value wrap_content can be used much like a preferred size in Java AWT or Swing.
It says to the View object, "Take as much space as you need to, but no more". The only
valid place to use these special attribute values is in the android:layout_width and
android:layout_height attributes. Anywhere else will result in a compiler error.

[ 20 ]

Chapter 1

We will need to access this TextView in our Java code later, in order to invoke its setText
method (which directly corresponds to the android:text attribute we used for the
placeholder text). A Java reference to a resource variable is created by assigning the resource
an ID. In this example, the ID is declared here as @+id/question. The AAPT will generate
an int value as an identifier for each resource of id as part of your R class. The ID attribute
is also needed for accessing resources from another resource file.

Time for action – adding a space for answers
While posing a question to the user is all very fine and well, we need to give them some
way to answer that question. We have several possibilities at our disposal: We could use a
RadioGroup with a RadioButton for each possible answer, or a ListView with an item
for each answer. However, to minimize the required interaction, and make things as clear
as possible, we use one Button for each possible answer. However, this complicates things
slightly, since you can't declare a variable number of Button objects in your layout XML file.
Instead, we will declare a new LinearLayout and populate it with Button objects in the
Java code.

1.

Under the TextView where we pose our question, you will need to add a
 element. While this element would normally have child
elements, in our case, the number of possible answers is varied, so we leave it as an
empty element.

2.

By default, a LinearLayout will place its child View objects horizontally alongside
each other. However, we want each child View to be vertically below each other, so
you'll need to set the orientation attribute of the LinearLayout:
android:orientation="vertical"

3.

We will need to populate the new ViewGroup (LinearLayout) later in our Java
code, so give it an ID: answers:
android:id="@+id/answers"

4.

Like our TextView and root LinearLayout, make the width fill_parent:
android:layout_width="fill_parent"

5.

Make the height wrap_content so that it doesn't take up more space than all the
buttons it will be populated with:
android:layout_height="wrap_content"

[ 21 ]

Download from Wow! eBook 

Developing a Simple Activity

The resulting code should look like this:


What just happened?
You may have noticed that for this example, we have no content in our new LinearLayout.
This may seem a little unusual, but in this case, we want to populate it with a variable
number of buttons—one for each possible answer to our multiple-choice questions.
However, for the next part of the example we need some simple content Button widgets
in this LinearLayout so that we can see the entire screen layout in action. Use the
following code in your layout resource file to add Yes!, No!, and Maybe? Button widgets
to the LinearLayout: