Android Programming In Java Starting With An App 3rd Edition James download
Android Programming In Java Starting With An App 3rd Edition James download
https://ebookbell.com/product/android-programming-in-java-
starting-with-an-app-3rd-edition-james-23180262
https://ebookbell.com/product/bluetooth-low-energy-in-android-java-
your-guide-to-programming-the-internet-of-things-tony-
gaitatzis-55557680
https://ebookbell.com/product/android-programming-in-kotlin-starting-
with-an-app-1st-edition-james-23180260
https://ebookbell.com/product/android-programming-for-beginners-build-
indepth-fullfeatured-android-9-pie-apps-starting-from-zero-
programming-experience-2nd-edition-horton-38076054
https://ebookbell.com/product/reactive-programming-in-kotlin-design-
and-build-nonblocking-asynchronous-kotlin-applications-with-rxkotlin-
reactorkotlin-android-and-spring-rivu-chakraborty-6855722
Android Game Programming Extend Your Game Development Skills By
Harnessing The Power Of Android Sdk A Course In Three Modules Horton
https://ebookbell.com/product/android-game-programming-extend-your-
game-development-skills-by-harnessing-the-power-of-android-sdk-a-
course-in-three-modules-horton-11418766
https://ebookbell.com/product/android-application-programming-with-
opencv-3-build-android-apps-to-capture-manipulate-and-track-objects-
in-2d-and-3d-joseph-howse-5476342
https://ebookbell.com/product/android-application-programming-with-
opencv-3-build-android-apps-to-capture-manipulate-and-track-objects-
in-2d-and-3d-1st-edition-joseph-howse-50195958
Kotlin And Android Learn To Architect And Develop Android Apps In The
Kotlin Programming Language Android Development With Kotlin Murdoch
https://ebookbell.com/product/kotlin-and-android-learn-to-architect-
and-develop-android-apps-in-the-kotlin-programming-language-android-
development-with-kotlin-murdoch-23720384
Kotlin And Android Learn To Architect And Develop Android Apps In The
Kotlin Programming Language Android Development With Kotlin Reuben
Murdoch
https://ebookbell.com/product/kotlin-and-android-learn-to-architect-
and-develop-android-apps-in-the-kotlin-programming-language-android-
development-with-kotlin-reuben-murdoch-27845784
Android Programming In Java:
Starting with an App
Third Edition
Mike James
I/O Press
I Programmer Library
Copyright © 2017 I/O Press
All rights reserved. This book or any portion thereof may not be reproduced
or used in any manner whatsoever without the express written permission of
the publisher except for the use of brief quotations in a book review.
The publisher recognizes and respects all marks used by companies and
manufacturers as a means to distinguish their products. All brand names and
product names mentioned in this book are trade marks or service marks of
their respective companies and our omission of trade marks is not an attempt
to infringe on the property of others.
In particular we acknowledge that Android is a trademark of Google.
2
Preface
3
This book is at an introductory level as far as Android development goes,
however it isn’t for the complete beginner. It is assumed that you can
program, but not necessarily in Java, which is arguably the most important of
all today’s programming languages and the original language of Android. Java
is a very standard object-oriented language and with the help of comments
that point out where it is significantly different you should find it easy to pick
up as you go along. Finally the development tool used is the latest version of
Android Studio because it doesn’t make sense not to use it or to use anything
else.
This edition has been updated to cover features introduced in Android
Studio 3. In particular, it includes the use of Java 8 and the lambda
expression which greatly simplifies event handling. As well as the latest
Android Studio it also covers ConstraintLaout 1.0.2 which includes Groups
and Barriers as well as a much improved editor.
Mike James
November 2017
4
Table of Contents
Chapter 1
Getting Started With Android Studio 11
The Language Choice........................................................................12
What You Need to Know..................................................................12
Making a Start...................................................................................12
Your First Program............................................................................14
First Look...........................................................................................18
The IDE..............................................................................................19
Basic Project Structure......................................................................19
Anatomy of an Activity.....................................................................20
Hello Layout Designer.......................................................................21
Inspecting the XML...........................................................................26
The Java.............................................................................................26
Getting Started with the Emulator ...................................................28
Summary...........................................................................................31
Chapter 2
Activity and User Interface 33
The MainActivity..............................................................................34
Inside the Activity.............................................................................35
View and ViewGroup........................................................................36
Creating Our First UI.........................................................................37
Properties...........................................................................................41
Events................................................................................................42
Connecting the Activity to the UI.....................................................44
Finding View Objects........................................................................48
Summary ..........................................................................................50
Chapter 3
Building a Simple UI 53
What's in the Palette..........................................................................54
The Button an Example....................................................................56
Positioning – the ConstraintLayout..................................................56
Sizing.................................................................................................64
The Component Tree........................................................................66
A Simple Button Example – Baseline Alignment............................66
Orientation and Resolution..............................................................68
A First App – Simple Calculator.......................................................73
Summary...........................................................................................81
5
Chapter 4
Android Events 83
The Lambda Approach.....................................................................83
Lambda Types...................................................................................85
Using a Lambda to Create an Event handler....................................86
Closure...............................................................................................88
Event Handler Using A Class............................................................89
Using Breakpoints.............................................................................92
Alternative Ways to Handle an Event..............................................93
Implement the Interface in the Activity...........................................94
Anonymous Classes..........................................................................95
Code Folding.....................................................................................98
Which Approach Should You Use?..................................................99
Summary.........................................................................................100
Chapter 5
Basic Controls 101
Basic Input Controls........................................................................101
Button Styles and Properties..........................................................101
All Properties...................................................................................105
Text Fields.......................................................................................107
The onEditorAction Event..............................................................110
CheckBoxes.....................................................................................111
Switches and Toggle buttons..........................................................112
Radio Buttons .................................................................................113
Summary.........................................................................................115
Chapter 6
Working With Layouts 117
Understanding Layouts...................................................................117
Layout Properties............................................................................118
Width and Height............................................................................120
Units................................................................................................120
A Control is Just a Box....................................................................122
Gravity.............................................................................................123
The FrameLayout............................................................................124
LinearLayout....................................................................................126
RelativeLayout.................................................................................130
Summary.........................................................................................134
6
Chapter 7
The ConstraintLayout 135
Automatic Constraints....................................................................136
Manual Constraints.........................................................................140
Bias Constraints...............................................................................143
Chains..............................................................................................145
A Chained Keypad..........................................................................147
Guidelines........................................................................................150
Groups.............................................................................................151
Sizing...............................................................................................152
Barriers............................................................................................157
Constraint Properties......................................................................160
Troubleshooting..............................................................................160
Summary.........................................................................................162
Chapter 8
Programming The UI 163
A UI Library.....................................................................................163
The View.........................................................................................163
Using setContentView.....................................................................164
The ViewGroup...............................................................................166
Programming Layout Properties.....................................................167
The View Hierarchy........................................................................169
XML Layout.....................................................................................169
Inflation Theory..............................................................................170
Finding View objects.......................................................................171
How to Build a UI?..........................................................................172
Summary.........................................................................................173
Chapter 9
Menus – Toolbar 175
Creating a Menu Resource..............................................................175
The Menu Tree................................................................................176
Displaying a Menu..........................................................................178
Using the Toolbar............................................................................179
Creating the App Bar ......................................................................183
Where's My Toolbar?.......................................................................184
Responding to Menu Events...........................................................184
Changing Menus in Code................................................................187
Controlling the Toolbar...................................................................190
Summary.........................................................................................191
7
Chapter 10
Menus – Context & Popup 193
The Context Menu..........................................................................193
Contextual Action Bar.....................................................................196
The Popup Menu.............................................................................200
Summary.........................................................................................203
Chapter 11
Resources 205
Why Use Resources?.......................................................................205
What are Resources?.......................................................................207
Drawables........................................................................................208
Values..............................................................................................211
IDs....................................................................................................212
Accessing Resources in Code – The R Object................................213
Conditional Resources....................................................................214
A Simple Localization.....................................................................218
Android Studio Translation Tools.................................................219
Summary.........................................................................................221
Chapter 12
Bitmap Graphics 223
Android Graphics............................................................................223
The Bitmap......................................................................................223
The ImageView Control..................................................................224
Canvas..............................................................................................225
A First Graphic................................................................................226
Transformations..............................................................................229
A Logical Approach to Transforms................................................232
Setting Your Own Coordinates.......................................................233
Simple Animation...........................................................................234
Timer and Threads..........................................................................236
Listing..............................................................................................241
Summary.........................................................................................243
8
Chapter 13
Life Cycle Of An Activity
Lifetime and State...........................................................................245
The Life Cycle of an App................................................................246
The Simple Approach.....................................................................247
Lifecycle Explorer...........................................................................248
Trying It Out....................................................................................249
Retaining State – the Bundle..........................................................250
Saving Additional UI Data..............................................................252
Complex UI Elements.....................................................................253
Advanced State Management.........................................................254
Summary.........................................................................................255
Chapter 14
Spinners 257
The Spinner and the Designer........................................................257
Introducing the ArrayAdapter........................................................259
Handling the Selection...................................................................261
Creating an ArrayAdapter from a Resource...................................265
Changing The List...........................................................................265
Summary.........................................................................................267
Chapter 15
Pickers 269
Working with Pickers......................................................................269
TimePicker.......................................................................................270
TimePicker in Code.........................................................................271
Updating the Time..........................................................................272
DatePicker........................................................................................273
Number Picker.................................................................................277
Multi-Digit Input.............................................................................281
Summary.........................................................................................285
Chapter 16
ListView 287
Understanding the Adapter............................................................287
Extending the ListAdapter Class....................................................288
Using the ArrayAdapter..................................................................289
Working with the Data....................................................................291
A Custom Layout.............................................................................294
A Custom ArrayAdapter.................................................................297
Reuse, Caching and General Layouts.............................................301
Custom Adapter..............................................................................304
Summary.........................................................................................306
9
Chapter 1
Android represents a big potential market. It is also the most open of the "big"
phone and tablet platforms. You can write a program for an Android and let
your friends have a copy, keep it to yourself or put it on sale in an app store.
Android phones and tablets are comparatively cheap and this makes it easier
to get started. What is even better, all the tools you need to create an Android
app are free. You don't need to pay anything to create, or distribute, your
Android apps. If you want to sell them using a well known marketplace there
may something to pay – there is a one-time fee of $25 to register for Google
Play, but you don't have to use any particular distribution method.
All that stands between you and your Android app is your imagination and
programming ability. I can't do much to improve your imagination, but I can
help with the programming side of things. If you are new to Android
programming this is the place to start.
In this book I will show you the fundamentals of Android programming. Not
the tips and tricks, but how to think about what is going on. You'll be
introduced to the general principles that will make it possible for you to
master anything that you encounter that is new in the future. It isn’t possible
to cover all of Android in one book as the subject is very large. Instead we
focus on the basics of creating a User Interface (UI) as all apps have to have
some way of interacting with a user.
There are many ways to create an Android app but Google's Android Studio is
an easy to use Android IDE – Integrated Development Environment – and it is
now the recommended way of doing the job.
Before Android Studio you had to use the Eclipse IDE and set up the SDK and
other pieces of software needed. This wasn't difficult, but Android Studio
eliminates extra steps and it makes programming Android easy. Put simply, it
is the way of the future and so worth your investment in learning it.
With the release of Android Studio Google stopped work on the Eclipse
plugin and this means that Android Studio really is the only way to develop
apps from now on.
You can get started in a few minutes and by the end of this chapter, have your
first working Android application.
11
The Language Choice
With the release of Android Studio 3 you now have a choice of programming
in Java or Kotlin. The advantage of Java is that it is a well known and well
supported language. In Android Studio 3 you can also program using features
from Java 8 including lambda functions. This greatly simplifies tasks such as
event handling and, while we will examine how to do event handling in Java
without lambda functions, using them is going to be the norm.
As the entire Android library is written in Java you really can’t avoid it. The
alternative language Kotlin is very easy to use and backwards compatible
with Java. There is very little risk in using it, but it is also helpful to know
enough Java to work with existing code.
The bottom line is that while Kotlin is an easier language to use, there are
advantages in knowing and using Java.
Making a Start
I'm not going to spend a lot of time explaining how to install Android Studio
in a step-by-step way as the Android website does a good job and it is more
likely to be up-to-date. It is worth, however, going over the basic principles.
Download the Android Studio package from Android Studio Home page:
https://developer.android.com/studio/
Install Android Studio which also installs all of the Android SDK and tools
you will need.
12
Windows:
1. Launch the downloaded EXE file,
android-studio-bundle-<version>.exe.
2. Follow the setup wizard to install Android Studio.
Mac OS X:
1. Open the downloaded DMG file,
android-studio-bundle-<version>.dmg
2. Drag and drop Android Studio into the Applications folder.
Linux:
1. Unpack the downloaded ZIP file,
android-studio-bundle-<version>.tgz,
into an appropriate location for your applications.
2. To launch Android Studio, navigate to the
android-studio/bin/
directory in a terminal and execute studio.sh. You may want to add
android-studio/bin/
to your PATH environmental variable so that you can start Android
Studio from any directory.
Accept any defaults that the setup program offers you – unless you have a
good reason not to. It installs not only Android Studio, but the SDK and the
13
virtual device system that lets you test your application. In most cases
Android Studio just installs with no problem.
Now you should be able to run Android Studio. If not the most likely cause of
the problem is the JDK and so re-installation is a best first option.
If you have already created some programs you might well see them listed in
Recent projects.
14
Assuming this is your first project select the option:
Start a new Android Studio project
You can ignore the details of the new project for the moment. All you have to
do is supply a name for your application - HelloWorld in this case. Make sure
you uncheck the Include Kotlin support option as you want to make use of
Java. Accept the other defaults that Android Studio has filled in for you.
When you click Next you are given the chance to pick what devices you are
targeting. Again simply accept the defaults:
15
Most of the time you will want to create apps that run on a version of Android
that captures the biggest market, but if this isn't a concern then it can be
better to select a more recent Android version.
The next page lets you select a template for your project. In this case change
the selection to Basic Activity. This gives you some additional generated code
which makes it easier to create an app that looks right. Every Android
application consists of at least one Activity and this template generates a
project with a single Activity ready for you to customize:
On the next page you can assign custom names for the various components of
your project that the template generates. For a real project you would assign
names that were meaningful, but in this case you can accept the defaults:
16
Finally you can click the Finish button and wait as Android Studio creates all
the files you need. Even a simple Android project has lots of files so again it
all takes time.
17
First Look
When everything is ready you will see Android Studio for the first time.
As long as everything has worked you should eventually, it takes about three
minutes or more, be presented with a view of your new project starting off in
the Designer. Click the Design tab to see the initial user interface:
Problems?
If you get any error messages then the chances are that your project hasn't
finished being processed. Wait a little while longer for the activity to stop. If
you look at the status line at the bottom of the window you will see a message
saying “Gradle Build Finished” when Android Studio has finished with your
new project.
If you still have problems it is worth trying the File,Invalidate Caches/Restart
command. This usually works for "Missing styles" and similar errors.
18
The IDE
Although there looks like a lot to master in the Android Studio user interface,
most of it you will only visit occasionally. The key things to notice are that
moving from left to right you have:
● The Project window
● The tool Palette and the Component Tree window
● The Designer or Layout Editor
● The Attributes window
Most of the time you will be using the Project window and the Attributes
window. You will also see different editors depending on what sort of file
you have selected. In this case you have by default a layout file,
content_main.xml, selected and hence you have a layout editor in the middle
of the screen.
Before we go into layout, which is one of the main topics of this book, it is
important that you know a little about the file structure of a project so that
you can navigate to its different parts.
It seems almost unbelievable that the simplest Android app you can create
involves so many files.
19
Don't panic. Most of the files that have been created are auto-generated and
most of the time you don't need to know anything about them, let alone open
or edit them. In fact, opening and editing auto-generated files really isn't a
good idea.
So let's focus on the files that matter to us.
For our simple program there are only two important files. One of them
determines the behavior of the Activity:
MainActivity.java
The other determines the visual appearance, or View, of the app:
content_main.xml
You can set which Activity is the one that the system starts, but by default it
is the single activity that you created and named when you set up the project.
You can change the default names but for the moment leave them as they are.
The java directory is, from your point of view, where most of the construction
of your app occurs so make sure you know where it is. The res directory is
where you store all of the resources, layouts, bitmaps, etc, that your app
needs.
So while things look complicated at the moment the only two project files
that matter to you, and your project, are MainActivity.java in the java folder
and content_main.xml in the res folder.
The two other folders in the java folder are concerned with creating tests for
your program. This is not something that we need to worry about when first
starting to write Android apps.
Anatomy of an Activity
An Android app is made up of one or more Activity classes.
You can think of an Activity as being something like a web page complete
with HTML to determine what displays and JavaScript to determine what it
does.
In the case of an Activity the layout is determined by the XML file in resource
(res) folder, this is often called the View, and the behavior is determined by
the code in the java folder.
The XML can be thought of as a markup language much like HTML or XAML.
It defines an initial layout for the screen when the app first runs. It is possible
to generate new layout components at runtime from the Java file. In fact, if
you really want to, you can dispense with the XML file and generate
everything from code, but as you will discover the XML markup approach is
much the best way to do the job because of the availability of the Designer.
20
So to be 100% clear in a Java project:
● The java file contains the code that makes your app behave in
particular ways.
● The .xml layout file contains a definition of the initial UI, the View, of
your app.
You can switch between editing the XML as text, and editing it in the drag-
and-drop designer simply by clicking on the tab. If you now click on the tab
the window will display the Designer, but be patient the first time you do this
it might take a few moments.
21
The Designer looks a little too much to take in when you first see it but you
will quickly get used to it. On the left is a Palette of all of the components or
controls - buttons, text, checkboxes and so on - that you can place on the
design surface:
In the middle is the design surface and this defaults to the screen size and
appearance of the Nexus 5. You can select other devices to work with.
22
There are, in fact, two views of the layout that you can use, the design and the
blueprint. By default you are shown the design view but you can display
either view using the menu at the top left of the design area.
You can display both views together, but in most cases available screen area
is the main issue and showing just one is the best option. The design view
shows you the layout as a close approximation to how it will appear on a real
device. The blueprint view doesn’t try to render the UI realistically but it does
provide you will more layout information to help you position and size
elements. Use whichever you are most happy with.
23
On the left, below the Palette, you have the Component Tree which shows
you the structure of your layout, that is how different UI components are
contained inside others. It shows you the structure of the XML file in an
easier to use form. You can use the Component Tree as an easy way of to
select individual UI components by clicking on their names. You can also
drag-and-drop UI components onto the Component Tree to position them
accurately within the hierarchy.
On the right you have the Attributes window that can be used to set the
properties, such as width, height, color and so on of any component in the
layout. If you have used any drag-and-drop designer then this will seem
familiar and if you have struggled with detailed layout using a markup
language, be it HTML, XAML or XML, you will appreciate how easy the
Designer makes building and testing a UI.
In the case of our sample program the only component is a single TextView
already containing the text "Hello World". A TextView is the standard
component to use when all we want to do is to display some static text.
24
You can modify the greeting text if you want to. Select the TextView
component either on the Nexus image or in the Component Tree and use the
Attributes window to find its Text property. Change this to read "Hello
Android World!":
Use the text field without the spanner icon. The properties with the spanner
icon next to them are used to set values that only show in the Designer. In
this case the text field without the spanner icon is the one that controls what
appears in your app at runtime.
You can use the Designer to create any UI you care to and you really don't
have to get involved in the XML that corresponds to the layout – unless things
go wrong or you need to do something so sophisticated that the Designer
doesn't support it.
25
Inspecting the XML
The Designer will automatically generate the XML needed to create the layout
for you and modify it as you change the layout. If you really want to see the
XML then all you have to do is select the Text tab at the bottom of the
Designer window:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.mikejames.helloworld1.MainActivity"
tools:showIn="@layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
You should find it fairly easy to understand – read the <TextView> tag for
example – but leave it to the Designer to create and modify it. The quantities
starting with @ are all references to things defined elsewhere in resource
files, more of this in chapter 11.
We will return to the Designer and the XML it generates later.
The Java
If you double click on the MainActivity.java file, or just select the
MainActivity.java tab, you will see the code it contains. Some of the code
might be hidden, but you can inspect it if you want to by clicking the +
button to expand it.
The important part of the code is:
public class MainActivity extends AppCompatActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
26
You can ignore the instructions that follow the setContentView function
because these set up the standard "extras" that every Android application now
supports – a floating ActionBar.
There are two other functions below the onCreate function, but ignore these
for the moment. They implement features you didn't really ask for which can
be useful, but not when you are just getting started.
The onCreate function is the only thing that matters at the moment. This
function is called when your app is run and it is expected to create the view
and do the actions the Activity is concerned with.
As our Activity doesn't really do anything much the only thing onCreate has
to do is first call the inherited OnCreate method, super.onCreate, to do all the
standard things and then use the setContentView function to select the XML
file that determines the layout of the Activity’s screen.
The line:
setContentView(R.layout.activity_main);
is the most important of all and really the only one that actually does
anything. It gets the resource object R that represents the layout as defined by
the XML file created by the Designer and makes it the current ContentView,
i.e. what is displayed on the screen. In other words, it makes the connection
between the layout you have defined using the Designer and stored in the
XML file, and the user interface that appears on the device’s screen.
You may be puzzled as to why you edited a resource file called
content_main.xml and yet the Java is loading a resource file called
activity_main.xml.
The answer is that, to make extending your app easier, Android Studio
creates two layout files, activity_main.xml that creates the "standard" controls
that are displayed and content_main.xml that you use to design your custom
UI. Of course, activity_main.xml contains a reference to content_main.xml.
This makes things more complicated for the beginner, but is a simplification
later on.
We have more to learn about the resource object R, but you can see that its
main role is to form a link between your Java code and the resources that
have been created as XML files by the Designer.
As this is all our Activity does, this is all the code we need. While I agree it is
hardly an "activity", it is enough to see the basic outline of an Android app
and to see how to get it running – which is our next job.
27
Getting Started with the Emulator
There are two distinct ways of running an Android app using Android Studio.
You can use the emulator or a real Android device. Eventually you will have
to discover how to run an app on a real connected Android device because
the emulator only allows you to test a subset of things and it is slow.
However, for the moment running your first app on an emulator is quite
enough to get started.
All you have to do is click the green run icon in the top toolbar – or use the
Run,Run "app" menu item. When you do this for the first time it will take a
while for the app to be compiled. Subsequent runs are much faster due to
optimizations introduced in Android Studio 2.
When your app is ready to be compiled you will see a dialog box appear
which allows you to either select a running emulator or start one going:
If no emulators are listed then you will have to create one. Select the Create
New Emulator button. This will present a dialog box where you can select the
device you want to test on.
The default is the Nexus 5 running API 25, Nougat, and for a first test you
might as well use this. If you need other devices you can use the AVD
(Android Virtual Device) Manager to define them.
If you see a message on the right of the screen “HAXM is not installed” then it
is a good idea to click the Install Haxm link just below. HAXM is an
accelerator that is used on Intel machines to make the Android Emulator run
faster. You don’t need it, but it does speed things up:
28
You can accept all of the defaults in this first run. You can monitor the
loading of the emulation in the Run window which appears automatically at
the bottom of Android Studio. You may see some warnings appear – these can
mostly be ignored.
The whole process takes some time the first time you do it. After the first time
the emulator is already running and the instant run feature tries to re-run
your app with the minimum changes:
29
Remember to wait until the Android operating system is loaded and you see
the familiar home screen before you start to wonder where your app is. Even
when it is loaded it is a good idea to give it a few seconds for Android Studio
to notice it and to upload your app:
In our case this isn't particularly impressive – just the words “Hello Android
World!” - but when you think of the journey traveled it really should
impress.
From this point on you can modify the code or the layout and run the app
again to see the effects of the changes. If anything goes wrong and you get in a
mess then simply delete the project and create it again from scratch.
You still have a lot to discover about how to extend the app and make it
useful, but the adventure has begun.
30
Summary
● Android Studio makes creating Android apps a lot easier than other
approaches and it is currently the only official way to do the job.
● An app has at least one Activity and this defines a screen layout, the
View, and a behavior. An Activity doesn't have to have a UI, but in
most cases it does have one.
● To create a simple application use the Basic Activity template with no
extras selected.
● The screen layout is controlled by an XML markup file,
Main_Activity.xml, stored in the res directory. There is also
content_main.xml, which is where we place our custom UI controls.
● Android Studio provides a drag-and-drop designer that allows you to
create a UI without having to work directly with the XML.
● The behavior of the app is controlled by a Java file, MainActivity.java
in our case, stored in the java folder. You can edit the code in the Java
file directly in Android Studio. The Java code has to load and display
the layout defined in the XML file.
● To run an app you need either an emulator based AVD or a real
Android device connected to the machine.
● When you run the app you can select which AVD or which hardware
device is used to test it. When you first start simply use the default
AVD, a Nexus 5.
● You can modify and re-run your app without having to restart the
AVD or any real hardware connected to the machine.
31
Chapter 2
So you know how to create an Android app, but do you really know how it
works? In this chapter we look at how to create a user interface (UI) and how
to hook it up to the code in the Activity.
We discovered in Chapter 1 how to use Android Studio to build the simplest
possible app. On the way we discovered that an Android app consists of two
parts – an Activity and a View. The Activity is the code that does something
and the View provides the user interface (UI). You can think of this duality as
being similar to the HTML page and the JavaScript that runs to make it do
something, or as a XAML form and the code behind.
The key idea is that an Activity is the code that works with a UI screen
defined by the View. This isn't quite accurate in that an Activity can change
its view so that one chunk of code can support a number of different views.
However, there are advantages to using one Activity per view because, for
example, this how the Android back button navigates your app – from
Activity to Activity.
A complex app nearly always consists of multiple Activities that the user can
move between like web pages but a simple app can manage quite well with
just one Activity. There is no hard and fast rule as to how many Activities
your app has to have, but it has to have least one.
If you are wondering if an Activity can exist without a View, the answer is
that it can, but it doesn't make much sense as this would leave the user with
no way to interact with your app. An Activity is active when its View is
presented to the user.
It really is a great simplification to think in terms of an Activity as a single
screen with a user interface.
If you want something to run without a UI then what you want is a service or
a content provider, which is beyond the scope of this book.
It is also worth making clear at this early stage that an Activity has only one
thread of execution – the UI thread – and you need to be careful not to
perform any long running task because this would block the UI and make
your app seem to freeze. That is, an Activity can only do one thing at a time
and this includes interacting with the user. If you write a program using a
single activity and it does a complicated calculation when the user clicks a
33
button then the activity will not be able to respond to any additional clicks or
anything that happens in the UI until it finishes the calculation.
In most cases the whole purpose of the Activity that is associated with the UI
is to look after the UI and this is what this book is mostly about.
Also notice that creating additional Activities doesn't create new threads.
Only one Activity is active at any given time, more of this later when we
consider the Activity life cycle in detail.
In this book we are going to concentrate on the single screen UI Activity
because it is the most common app building block you will encounter, and it
is even where most complex apps start from.
The MainActivity
There is one activity in every project that is nominated as the one to be
launched when your app starts. If you use Android Studio to create a new
Basic Activity app called SimpleButton and accept all the defaults, the
startup Activity is called MainActivity by default. You can change which
Activity starts the app by changing a line in the app's manifest.
The Manifest is a project file we haven't discussed before because if you are
using Android Studio you can mostly ignore it and allow Android Studio to
construct and maintain it for you, but it is better if you know it exists and
what it does.
The Manifest is stored in the app/manifests directory and is called
AndroidManifest.xml.
It is an XML file that tells the Android system everything it needs to know
about your app, including what permission it requires to run on a device.
In particular it lists all of the activities and which one is the one to use to start
the app.
If you open the generated Manifest, by double-clicking on it, you will see a
little way down the file:
<activity
android:name=".MainActivity"
android:label="SimpleButton" >
This defines the Activity the system has created for you and the lines just
below this define it as the startup Activity:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
34
Notice that the choice of which Activity starts the app has nothing to do with
what you call it, i.e. calling it MainActivity isn't enough.
For the moment you can rely on Android Studio to look after the Manifest for
you. In most cases you will only need to edit it directly when you need to
correct an error or add something advanced.
35
you created using the Designer and the layout that appears on the device's
screen.
It is worth looking a little closer at the way that the layout file is specified
because this is a general way that Android lets you access resources. There is
a whole chapter about resources later but it is still worth an introduction
now.
The R object is constructed by the system to allow you to access the resources
you have placed in the resource directories. For example, in onCreate the use
of R.layout.activity_main returns an integer value, its id, that allows the
setContentView method to find the activity_main XML layout file. In general
all resources are found via the R object, think of it as an index of resources.
36
That is, you can drag-and-drop a button onto the Designer and it will
automatically generate the XML needed to create it and specify where it is
and all of the other details you set.
That is, at the surface level there are three ways to create the UI:
1. You can write Java code to generate the necessary Java objects.
2. You can write XML tags and use the system to convert the XML to the
same Java objects.
3. You can use the Designer to interactively create the UI and generate
the XML file which is then converted into the Java objects
needed. You can think of this as:
drag-and-drop layout -> XML -> Java View objects
Being able to work with the UI in an interactive editor is one of the great
advantages of using Android Studio and, even if you know how to edit the
XML layout file directly, it isn't a feature you should ignore. It is nearly
always a good idea to use the layout editor as the first step and apply any
tweaks, if necessary, to the XML file later.
37
The content_main.xml is where you create all of your UI. There is another
layout file, but as explained in Chapter 1 this simply provides the standard
elements in a UI like the AppBar. Notice that because of this you can see UI
components in the Designer that you cannot edit - they belong to the other
layout file.
To remove "Hello World" all you have to do is select it and press the delete
key:
Notice that there is an undo command, Ctrl-Z, if you delete something by
mistake.
Next select the button in the Widgets section of the Palette by clicking on it
and drag it to the design surface:
38
If you now place the cursor over the design area you will discover that as you
move it various alignments are indicated by lines:
To position the button simply click and a full button, complete with the
default caption Button, will appear.
However, simply dropping the button on the design surface isn't quite
enough. If you just do this the button will be positioned but without any
positioning constraints. If you try running the program you will find that the
button sometimes vanishes on the emulator or real device. The reason is that
with no constraints to its positioning applied it rises to the top of the screen
and is hidden behind other controls.
This behavior is characteristic of the ConstraintLayout, more of which later.
For the moment we just need to apply some constraints to the button.
The simplest solution is to click on the Infer constraints icon and let Android
Studio work out how to position the button:
When you click this button constraints are added according to where the
Button is positioned. At the moment exactly what constraints you end up
applying matters less than the simple fact that there are some.
39
In the screen dump below the button is constrained to be a fixed distance
from the top and right-hand side. Notice that you can position the button and
then click the Infer constraints button to set the constraints needed to keep
the button in its location:
Now you have a button on the UI ready to go, let's add a TextView Widget in
exactly the same way – click on its icon in the Palette, position in the
Designer and click to set the position. Notice that Android Studio provides
positioning information to help you align components of the UI. Again you
need to click the Infer constraints icon to position the TextView. The simplest
thing to do is position the TextView where you want it and then click the
Infer constraints icon to set the constraints needed for that position:
40
Notice that Android Studio provides positioning information to help you
align components of the UI. The simplest approach to creating a layout is to
place the components where you want them and then click the Infer
constraints icon to apply constraints to fix their position. In practice these
constraints may not be exactly what you need but it gives you a starting point.
That's about it and in fact creating a complete complex UI is just more of the
same, just a matter of picking components from the Palette and positioning
them on the design surface.
If you now run the program, by clicking the green Run icon (refer back to
Chapter 1 if you don't know how to do this) you will see your new UI:
Of course it doesn't do anything, even if you can click the button. The button
does click, but there is no code connected to the button click event to say
what should happen, something we will deal with very soon.
Properties
Our next task is to change the caption on the button. Recall that objects have
properties and methods. Things like caption text, background color and so on
for UI widgets are represented as properties. You can change properties in
code, or at design time you can use the Attributes window on the right-hand
side of the screen.
41
If you select the button and examine the Attributes window on the right you
will find the button's text property. This currently contains the value
"Button". If you change this to "Click Me!" and re-run the app you will see that
the Button's caption has changed:
You can set the initial properties of any of the widgets that you have placed in
the UI. There are a great many properties and we need to spend some time
looking at some of them. However, for the moment the important thing is that
you see how easy it is to change a property using the Attributes window.
As you might guess, the property that you changed results in a change in the
XML file defining the layout. Recall that the general principle is that the
Designer creates the XML file that you could have created by hand without
any help from the Designer. In this sense, the Designer doesn't add anything
to the process, other than being much easier.
Events
Now we want to do something when the button is clicked. Android supports
a complete event-driven UI. So what we need to do next is define a method,
or function, that is called when the button is clicked.
If you are familiar with other languages you might find the Java way of
working with events strange and convoluted. It is, and we will have to come
back to discover the full story of how events are implemented later. The good
news is that Java events are much simpler in Java 8 and now Android Studio
supports this. While you do need to know the original ways of creating event
42
handlers it is always much easier to use Java 8 and its lambda functions in
particular. How to create event handlers is discussed in detail in Chapter 4.
There are a number of different ways to specify an event handler, but the
simplest is to use the Designer to generate the XML needed for the system to
hookup the event handler to the event. This is not an approach that you can
use all of the time. It only works for the click event, but it gets you started.
If you have used something like Visual Studio, it is also worth pointing out
that Android Studio doesn't automatically create event handlers for you. In
the case of Android Studio you have to create a function and then assign it as
the onClick handler. The reason for this apparently unhelpful approach is
that Java events are much more involved than .NET or JavaScript events.
Using the Designer approach, method click event handlers are simply public
methods of the current Activity with the signature:
void method( View v)
Just in case you have missed or forgotten what a function's signature is:
A function’s signature is the number and types of the parameters it accepts.
Functions with the same name but different signatures are considered to be
different functions. In this case the function takes a single parameter, which is
a View, and returns void, i.e. nothing.
You can call the method anything you like, but in most cases it helps to
specify exactly what the event it handles is. In this case we want to handle
the button's onClick event – which occurs when the user clicks on the button
with a mouse or more likely taps on the button using a touch sensitive
device.
Load the MainActivity.java file into the code editor and add the following
method:
public void buttonOnClick(View v) {
// do something when the button is clicked
}
This needs to be added directly following the onCreate method, or anywhere
that makes it a method of the MainActivity class.
43
With all this code out of the way, now switch back to the Designer, select the
button, find the onClick property in the Attributes window to enter or select
buttonOnClick:
Sometime the IDE is slow to notice that there is a suitable method and you
have to type the method’s name in. Notice that you don't type in parameters,
just the name of the method.
That's all there is to it. You define your event handler with the correct
signature and return type and set the appropriate onClick property in the
Attributes window.
When it comes to other types of event you have to do the job in code – the
XML/Designer method only works for onClick.
44
In the case of the View object that caused the event this is very easy as it is
passed to the event handler as the only argument of the call. So if the event
handler is:
public void buttonOnClick(View v) {
and the event handler is only hooked up to the button, then you can be 100%
sure that v is the button object when the event occurs. If you want to change
the button's caption you could just use its setText method to change its
value.
Note: if you aren't used to Java then it is worth pointing out that generally all
Java frameworks follow the rule that if an object has a property called
myProperty, visible as such in the Attributes window, then in code you set it
using setMyProperty and retrieve it using getMyProperty.
So, in principle, all you have to write is:
v.setText("I've Been Clicked!");
However, this doesn't work because v is declared to be a general View object
which doesn't have a setText method – not all View objects have text to set.
To call the Button's setText method we have to cast v to its correct type,
namely a Button.
Note: Casting is where you tell the system the type of the object you are working
with. If classB is a subclass of classA then you can treat a classB object as a
classA - after all it has all of the methods and properties that classA does by
inheritance. However, if you want to make use of a property or method that
only classB has then you need to cast the reference to the classB object to make
its type clear.
For example, assuming classB inherits from classA:
classA myObject = new classB();
creates an instance of classB but myObject is declared to be of type classA. This
is fine but you can only access the methods and properties of the classA object.
However, if you try:
myObject.classBMethod();
then it will fail if classBMethod only exists in classB. To use the classB method
you have to cast myObject to its real type:
(classB) myObject
You can store a reference to the cast in a new variable:
classB myClassBObject = (classB) myObject;
and then call the method:
myClassBObject.classBMethod();
or you can just do the cast on the fly at the cost of an extra pair of parentheses:
((classB) myObject).classBMethod();
45
If you simply change the code to cast the v object to a Button object, i.e.
(Button) v, you will discover that Android Studio flags an error by showing
Button in red. If you hover over the red symbol you will see the exact error
message:
This is because you have used a class without importing it. You may see other
classes, View, for example highlighted in red as which classes are imported
by default depends on the exact project template you are using.
Any class that you use has to be listed at the top of the program in an import
statement. Whenever you see a "Cannot resolve symbol" error message the
most likely cause is that you haven't imported the class.
This can be a tedious business but Android Studio has some help for you. If
you click on the error symbol you will see a blue hint message:
If you look at the hint message it suggests pressing Alt+Enter which is always
good advice because it produces a list of possible fixes for the problem:
You can implement the fix simply by selecting it from the list.
In this case you have to add the class definition to the start of the program.
import android.widget.Button;
You can do this manually, i.e. you can type it in, or just select the first option.
The import is added and in a moment the red errors disappear.
46
If you hover over the corrected Button class name you will also see a light
bulb:
Android Studio offers you hints on improving your code even when there are
no errors – look out for the light bulbs. If you click on this one it will offer to
split the declaration and the assignment as being better style. Android Studio
is full of hints and offers to make your code better at every turn – you don't
have to accept them.
For the moment let's stick with the single line:
Button button=(Button) v;
Now we have the button object we can call its setText method:
button.setText("I've Been Clicked!");
The complete event handler is:
public void buttonOnClick(View v) {
Button button=(Button) v;
button.setText("I've Been Clicked!");
}
Now if you run the program you will see the button's caption change when
you click the button.
This is a common pattern in making your UI work – event handlers change
the properties of View objects to modify the UI. Notice that this approach
only works if you know the type of the object that caused the event and called
the event handler. If your event handler is only connected to a single
component then you do know the type of the object that caused the event. If
it isn't, or if you want to modify the properties of a View object that isn't the
subject of the event, then you have to find it. This is exactly what we are
going to do next.
47
Finding View Objects
Now suppose we want to do something to one of the other components in the
View. In this case we have to find the object that represents the component
without the help of the event handler's argument. For example how do we
find the TextView that we placed below the button?
In the event handler the Button is the object that caused the event to happen
so it is already found, but how do you find another component in the layout?
This is a very standard pattern in working with View objects from the
Activity. First you make use of the R object to find the component's id. In this
case the TextView has been given the id textView by default so we can use:
R.id.textView:
and this returns a unique integer that identifies the component.
Next we use the Activity’s
findViewById(int)
method which takes the integer id and returns the Java object corresponding
to id.
Of course this is returned as a View object because findViewById doesn't
know the type of the object it returns any more accurately. So we have to cast
to make use of the TextView object.
Putting all this together gives:
TextView myTextView=(TextView) findViewById(R.id.textView);
Once again Android Studio will complain about TextView and if you press
Alt+Enter it will add the class import to the start of the program for you:
import android.widget.TextView;
Now that you have the TextView object you can use the setText method to
change what it displays:
myTextView.setText("You Clicked My Button!");
The complete event handler is:
public void buttonOnClick(View v) {
Button button=(Button) v;
button.setText("I've Been Clicked!");
TextView myTextView=(TextView)findViewById(R.id.textView);
myTextView.setText("You Clicked My Button!");
}
48
If you now run the program you will see that you are informed twice of the
fact that this very important button has been clicked:
You may think that this is all very small stuff and nothing like a real app, but
this is how building a UI works in Android.
You now know how to design a single screen app using the widgets available
in the Designer’s Toolbox and how to hook them up to handle their click
events, find the Java object that represents them and how to call methods that
modify them.
Apart from the fine detail of how each of the widgets works – radio buttons,
checkboxes and so on – you now have the general outline of how to build a
single screen app.
49
Summary
50
Exploring the Variety of Random
Documents with Different Content
Conditions precedent to Proof.
Barrels for arms of the first class shall not be qualified for proof until they shall be in a fit and proper state for setting up.
Barrels for arms of the third class shall not be qualified for proof until they shall be in a fit and proper state for setting up,
with the proper breeches in; and all barrels lumped for percussioning shall be proved through the nipple hole, with the
proper pins or plugs in.
Barrels for arms of the second and fourth classes:
For provisional proof:—If of plain metal, shall be bored and ground, having plugs attached, with touch-holes drilled in the
plugs, of a diameter not exceeding one-sixteenth of an inch. If any touch-hole shall be enlarged, from any cause whatever,
to a dimension exceeding in diameter one-tenth of an inch, the barrel shall be disqualified for proof. Notches in the plugs
instead of drilled touch-holes shall disqualify for proof. If of twisted metal, they shall be fine-bored, and struck up, with
proving plugs attached, and touch-holes drilled as in the case of plain metal barrels.
For definitive proof:—The barrels, whether of plain or twisted metal, shall be in the finished state, ready for setting up, with
the breeches in the percussioned state, break-offs fitted and locks jointed; the top and bottom ribs shall be rough struck up,
pipes, loops, and stoppers on. All rifle barrels must be rifled; the top and bottom ribs of double barrels shall be struck up,
pipes, loops, and stoppers on, the proper breeches in, and the thread of the screws shall be sufficiently sound and full for
proof.
Barrels for revolving arms of the fifth class shall have the cylinders with the revolving action attached and complete.
Barrels for breech-loading arms of the fifth class shall be subject to provisional proof, according to the class to which they
belong, and to definitive proof when the breech-loading action is attached and complete.
Marks of Proof.
The marks applicable to the definitive proof shall be the proof and view marks now used by the two companies respectively.
The marks applicable to the provisional proof for the Gunmakers Company shall be the letters (G.P.) interlaced in a cypher
surmounted by a lion rampant, and for the Birmingham Company shall be the letters (B.P.) interlaced in a cypher surmounted
by a Crown.
London marks.
Birmingham marks.
The Scale following shows the Proportions of Gunpowder applicable under the foregoing Rules and
Regulations to the Proof of the various Classes of Arms as distinguished by the Trade Numbers
indicating the Calibre.
N.B.—Revolving Arms of the Fifth Class shall be proved once only, and such Proof shall be by the Scale laid down for
definitive Proof of the Fourth Class.
As soon as a number of gun barrels are loaded according to the
foregoing scale, they are taken to a house or detached building,
standing apart from other offices. (The woodcut represents the
interior accurately.) The house is lined throughout with thick sheet
iron, and the windows, which resemble Venetian blinds, are
constructed of the same metal. Iron frames are laid the whole length
of the room; on these the barrels of various qualities, when about to
be fired, are placed. In the front of these frames lies a large mass of
sand, to receive the balls. Behind the frame, on which the twist
barrels are fixed, lies another bed of sand; in which, on the recoil,
the barrels are buried. Behind the frame, on which the common
barrels or muskets are tried, a strong iron bar is placed, having a
number of holes large enough to receive the tang of the breech, but
not the barrel. The barrels being thus fixed, it is impossible for them
to fly back. A groove runs along the whole length of each frame, in
which the train of powder is strewed to ignite the charges, upon
which the barrels are laid, with the touch-holes downwards.
When everything is ready for the proof, the windows are let close
down, the door is shut and secured, and an iron rod heated red hot
is introduced through a hole in the wall. On igniting the train, a
tremendous explosion takes place. The windows are then drawn up,
the door opened, and the smoke dissipated. The twist barrels are
found buried in the sand, the common ones are thrown forwards;
some are found perfect, others burst to pieces. It is rarely that best
barrels are found burst; more frequently they are bulged, or swelled
out, in places which are faulty, or of a softer temper. Those that are
found perfect, are then marked with the provisional punch of
different sizes (but having the same impression), according to the
quality of the barrel. In London and Birmingham they have now an
additional punch, containing the number of the bore by which the
barrel has been tried. This mark easily enables the observer to
discover whether the barrel has had any considerable quantity bored
out after proving. Those that are bulged are sent to the maker, who
beats down the swellings, and sends back the barrels to be proved
again. They generally stand the second proof, though we have
known a barrel undergo four proofs before it was marked. The
common barrels are required to stand twenty-four hours before they
are examined; when, if not burst, any holes or other material
imperfections are made quite apparent by the action of the
saltpetre. Such barrels are, of course, sent back unmarked. Those
that are found satisfactory are duly stamped and taken home.
The importance of the gun trade to England may be estimated from
the number of barrels proved during the last year, 1857, of which the
following is a correct statement:—
Provisional Proof.
“Science begins at the point where mind dominates matter, where the attempt is
made to subject the mass of experience to the scrutiny of reason. Science is mind
brought into connection with nature.”—Cosmos.
Punched a Equal in
Oz. Drachms. boiler plate force to
1 ball 12 of powder Half-inch thick 46,875 lbs.
1 „ 10 „ 7-16ths „ 41,015 „
1 „ 8 „ 6-16ths „ 35,155 „
1 „ 1
6 ⁄2 „ 5-16ths „ 29,295 „
1 „ 5 „ 4-16ths „ 23,437 „
1 „ 3 1⁄4 „ 3-16ths „ 17,578 „
1 „ 2 „ 2-16ths „ 11,718 „
The nipples now in general use have the smaller orifice at the
bottom, and, being lined with platina, never foul. Experience has
shown that admitting the gunpowder into the nipple “is not
advantageous,” especially with large grained powder; by
constructing the nipple with the small orifice at the bottom, the
largest grain can be used beneficially. As the velocity of the
fulminating gas is much greater than “a train” of gunpowder ever
can be, quickness is also gained by their adoption. I have used them
for many years with great success; nothing but cost deters their
general adoption. The passing of the flame through the very small
opening in the platina, by this very high impingement, increases its
heat to a great extent, ensuring explosion.
The true science of gunnery consists in knowing that a certain force
is requisite to effect a certain purpose, or, in other words, to kill at a
certain distance; and also how to arrange that force so as to effect
the purpose without having any extra force, or any waste of powder,
nor yet too little, but with a corresponding result: a sufficiency;
neither more nor less. This we have shown is attainable by the
mechanical arrangement of granulation; for it is useless to use less,
or to use an iota more of fine grain powder, if the size larger will
effect the purpose without that iota. Propellant velocity is the grand
desideratum in all gunnery; the obtainment of this, to the greatest
extent, is the power of killing at the greatest distance: all ranges are
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
ebookbell.com