Upload
gteodorescu
View
222
Download
0
Embed Size (px)
Citation preview
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 1/77
ZetCode Android tutorial
This is Android development tutorial. The tutorial is suited for beginners. After reading this
tutorial, you will be able to program non-trivial Android applications.
Android
Android is a Linux based operating system designed for mobile devices such as smartphones
and tablet computers. It is also used for various networking euipments, smart T! systems,
wrist watches and household appliences. Applications for Android are developed in a
customi"ed version of the #ava programming language.
Introduction
This is an introductory Android development tutorial. The purpose of this tutorial is to get
you started with the develompent of applications in Android. The tutorial has been created
and tested on Linux.
Android
Android is a Linux based operating system designed for mobile devices such as smartphones
and tablet computers. It is also used for various networking euipment, smart T! systems,
wrist watches and household appliences. Applications for Android are developed in a
customi"ed version of the #ava programming language.
Android was developed in $%%& by a 'alifornian company which was later purchased by
(oogle. (oogle created the Android )pen *ource +roect for maintaining and developing of
the Android )*. Android is being developed uickly new versions of Android are freuently
being released. The Android code names are being choosed after some sweets, like onut,
(ingerbread or #elly /ean. evelopers can publish their applications in an online Android
market called Google Play. /efore an application is published on a (oogle +lay market, it
must be prepared for release, properly versioned and digitally signed. Android users use a
built-in application to search for applications on Android market and install them.
Android architecture
Android is based on a Linux kernel. The kernel is responsible for the device drivers,
memory management, process management and networking. Above the kernel, there are core
libraries and Android runtime. The libraries are '0'11 libraries that provide services such as
data storage, screen display, multimedia and web browsing. These capabilities are exposed
indirectly to developers through the Android application framework. The Android runtime
consists of the alvik virtual machine and the core #ava application libraries. alvik is a
virtual machine specifically developed to run #ava based applications on Android. It is
different from the standard #ava !irtual 2achine 3#!24. The next layer up is the application
framework . It is a set of A+Is to provide services to Android applications. It handles
application life cycle through Activity 2anager, notifications through 5otification manager,resources through 6esource 2anager, a set of graphical widgets 3called !iews in Android4,
7
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 2/77
package management trough +ackage 2anager and others. )n top of it sits the applications
layer. It is where our own applications are running. Android also has built-in applications
which can provide additional services to our applications. 8e can have access to browser,
*2*, calendars, maps or contacts.
Terms and concepts
Android application is an archive file with an .apk suffix. 9ach Android application lives on
its own in a security sandbox. An activity is a single screen with a user interface. An
application can have one or more activities. Activities are independent of each other.
Activities are subclasses of the Activity class. A service is an application component that
runs in the background. It does long running operations. It is a subclass of a *ervice class. A
content provider manages a shared set of application data. It is used to access : modify data
in the filesystem, *;Lite database or the web. It is a subclass of the 'ontent+rovider class. A
broadcast receiver is a component that receives broadcast notifications from the system or
applications. A broadcast receiver is implemented as a subclass of /roadcast6eceiver. 9ach
broadcast is delivered as an Intent obect. An intent is an asynchronous message. It is an
abstract description of an operation to be performed. Intents are used to navigate through
activities. Activities, services and broadcast receivers are activated through intents. A iew
class is a basic building block of a user interface. It is responsible for drawing and event
handling. A !iew is a base class for widgets, which are used to create <I components like
buttons or check boxes. A iewGroup is an obect that holds other !iew 3and !iew(roup4
obects in order to define the layout of the interface.
9ach Android application must have an AndroidManifest.xml file in the root directory. This
file presents essential information about the application to the Android system. The API level
is an integer value that uniuely identifies the framework A+I of the version of the Android platform. 9ach new Android platform brings new modifications to the Android application
framework. An !mulator is a virtual mobile device that runs on a computer. It is used to
develop and test Android applications without using a physical device. An Android irtual
"evice #A"$ is an emulator configuration that models an actual physical device such as
smartphone. 8e can create multiple A!s and test our applications on different hardware
platforms that use Android )*.
Installation
To start developing for Android, we need to download the Android *= 3*oftware
evelopment Toolkit4. There are two options. An 9clipse AT bundle or single *= tools.8e will go with the latter.
$ ls -sh android-sdk_r21-linux.tgz88M android-sdk_r21-linux.tgz
'urrently the file to dowload for Linux is android-sdk>r$7-linux.tg".
$ tar -xzvf android-sdk_r21-linux.tgz
8e uncompress the "ipped archive. The archive is extracted to the android-sdk-linux
directory.
$
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 3/77
$ pwd/home/an!odnar/!in/android-sdk-linux$ lsadd-ons platforms "# %eadme.txt tools
The Android *= archive initially contains only the basic *= tools. 8e need to dowload
additional tools with the *= manager. The Android *= manager is launched with theandroid command line tool.
?igure@ Android *= 2anager $ lsadd-ons platforms samples sour&es tempdo&s platform-tools "# %eadme.txt s'stem-images tools
These are the contents of the android-sdk-linux directory after installing additional tools.
export ()*+,$()*+/!in/android-sdk-linux/toolsexport ()*+,$()*+/!in/android-sdk-linux/platform-tools
8e add the tools and platform-tools directories to the +AT variable.
Android AVD
The Android A! 3Android !irtual evice4 is a is an emulator configuration that enables us
to model an actual device by defining hardware and software options to be emulated by the
Android 9mulator.
$ android avd
The command starts the Android !irtual evice 2anager.
?igure@ 'reating new A!
&
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 4/77
'licking on the 5ew button we start a dialog to create a new Android !irtual evice. In the
dialog we give the A! a name, select a hardware profile of the device, choose the A+I level
of the target or a dedicated storage area on our development machine.
$ android list avd
)vaila!le )ndroid irtual #evi&es 0ame )# (ath /home/an!odnar/.android/avd/)#.avd *arget )ndroid .2 3)(4 level 156 )74 armea!i-v5a "kin 2x8--------- 0ame )# (ath /home/an!odnar/.android/avd/)#.avd *arget )ndroid .2 3)(4 level 156 )74 armea!i-v5a "kin 2x2
The android list avd command shows all available Android !irtual evices.
Android Emulator
The Android emulator is a virtual mobile device that runs on our computer. It lets us develop
and test Android applications without using a physical device.
$ emulator -avd )#1 9
8e use the emulator command to start the emulator. 8e specify the name of the created
Android !irtual evice.
?igure@ 9mulator of a $.BC 3$D%x&$% ldpi4 device
D
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 5/77
The emulator is unlocked using the ?$ key. To list available applications, we click on the
circle icon. An application is uninstalled by clicking on the menu hardware button and
selecting 2anage apps option. Then we click on the icon of the application to uninstall and
click the <ninstall button.
This chapter was an introduction Android application development.
%irst Android application
In this chapter of the Android development tutorial we will create our first Android
application.
The application will ust display a message on the screen.
$ mkdir :irst
$ &d :irst/
8e create a ?irst directory and make it the current working directory.
$ android &reate proe&t --target android-15 --name :irst ;< --path . --a&tivit' Main)&tivit' --pa&kage &om.zet&ode.first=reated dire&tor'/home/an!odnar/programming/android/:irst/sr&/&om/zet&ode/first)dded file ./sr&/&om/zet&ode/first/Main)&tivit'.ava=reated dire&tor' /home/an!odnar/programming/android/:irst/res=reated dire&tor' /home/an!odnar/programming/android/:irst/!in...
8e create a new Android proect with the android &reate proe&t command. The target
option specifies the Android application framework version. The name option determines the
name of the proect. The path is the location of our proect directory. The activity is the name
of our default activity. ?inally, the package is the name of the package namespace for our
proect. The command creates a #ava file for the main activity, several directories and E2L
files.
$ ls)ndroidManifest.xml !in li!s proguard-proe&t.txt resant.properties !uild.xml lo&al.properties proe&t.properties sr&
These are the files and directories created by the android &reate proe&t command. The
AndroidManifest.xml file describes the fundamental characteristics of the application. The
source files of the application reside in the src directory. In the res directory, we have the
applicationFs resource files. The Android application archive file will be created in the bin
directory. The libs directory is used to store additional libraries. The ant.properties and
build.xml files are the Ant files used to build the proect. ?inally, the local.properties and the
project.properties are property files of the Android proect.
Android2anifest.xml>?xml version,@1.@ en&oding,@utf-8@?<>manifest xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ pa&kage,@&om.zet&ode.first@ androidversion=ode,@1@
G
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 6/77
androidversion0ame,@1.@< >appli&ation androidla!el,@Astring/app_name@ androidi&on,@Adrawa!le/i&_laun&her@< >a&tivit' androidname,@Main)&tivit'@ androidla!el,@Astring/app_name@< >intent-filter<
>a&tion androidname,@android.intent.a&tion.M)40@ /< >&ategor' androidname,@android.intent.&ategor'.B)C0=+D%@ /< >/intent-filter< >/a&tivit'< >/appli&ation<>/manifest<
This is the proect manifest file. It describes some basic characteristics of the Android proect.
The file provides the package name, which is com."etcode.com in our case. It contains the
name of the default activity. The @string/app_name and @drawable/ic_launcher are
resource values. The string resource values are set from the strings.xml file located in the
res0values subdirectory. The image resources are located in the drawable subdirectories of the
res directory. The <intent-filter> element of the main activity declares its capabilities. Itspecifies what the activity can do. The two intents specify that the activity is a main entry
point of the application, it can be the initial activity of a task and is listed in the top-level
application launcher.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<:irst program>/string< >string name,@messsage@<:irst )ndroid program>/string<>/resour&es<
In the strings.xml file we have one element which defines the resource value referenced from
the AndroidManifest.xml file. The file is located in the res0values subdirectory. 8e change
the value of the first element 3from F2ainActivityF to F?irst programF4. The name of the
application is shown in the list of the applications in the emulator. 8e add the second
element. It is referenced from the main.xml file.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@
androidla'out_height,@fill_parent@ <>*extiew androidla'out_width,@fill_parent@ androidla'out_height,@wrap_&ontent@ androidtext,@Astring/message@ /<>/BinearBa'out<
This is the main.xml file located in the res0layout subdirectory. It defines the layout of an
Activity. The application loads the layout for an Activity in the on=reate36 method. In our
case we have a vertical linear layout with one Text!iew widget.
2ainActivity.ava
H
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 7/77
pa&kage &om.zet&ode.firstE
import android.app.)&tivit'Eimport android.os.7undleE
pu!li& &lass Main)&tivit' extends )&tivit'
F /GG =alled when the a&tivit' is first &reated. G/ AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.main6E II
This is the MainActivit.java source file. 8hen the activity is first created the on=reate36
method is called. The method loads the activity layout defined in the main.xml file.
Building the application
8e use the ant tool to build the Android application.
$ ant de!ug
8e execute the ant de!ug command in the proect root directory. There are two build
targets. ebug and release. 8e will use the debug build target. The release build needs some
additional work with signing.
$ ant de!ug install
It is possible to build and install the application in one step using the ant de!ug install
command.
$ ls -1 !in)ndroidManifest.xml)ndroidManifest.xml.d!uild.prop&lasses&lasses.dex&lasses.dex.d
:irst.ap_:irst.ap_.d:irst-de!ug.apk:irst-de!ug-unaligned.apk:irst-de!ug-unaligned.apk.darlist.&a&heproguard.txtres
The final Android package is created in the bin directory. The name of our archive file is
!irst-debug.ap" .
B
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 8/77
Running the application
8e install the application to the emulator and start it from it.
$ emulator -avd )#2 9
The emulator is started with a specific android virtual device.
$ ad! install !in/:irst-de!ug.apk
The ad! install command installs the application on the emulator.
?igure@ ?irst program
8e did not use a custom icon, so the built-in icon is used. ?rom the applications list we select
the ?irst program application. The application is launched.
?igure@ The ?irst program screen
8e can see the message that we have specified in the strings.xml file.
This chapter was an introduction Android application development.
&utton widgets
In this chapter of the Android development tutorial we will present button widgets.
A 7utton class represents a push button widget in Android. The full package path for the
button class is android.widgets./utton. /uttons are clicked to perform an action. A button can
display text or an icon. )r both. 9vent handlers for /utton click events are defined with the
android#on$lic" attribute of the /uttonJ element or programatically by setting the
set%n$lic"&istener'(iew.%n$lic"&istener).
Button
In the first example we define a button that closes an activity when pressed.
K
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 9/77
Android2anifest.xml>?xml version,@1.@ en&oding,@utf-8@?<>manifest xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ pa&kage,@&om.zet&ode.finish@ androidversion=ode,@1@ androidversion0ame,@1.@<
>appli&ation androidla!el,@Astring/app_name@androidi&on,@Adrawa!le/i&_laun&her@< >a&tivit' androidname,@Main)&tivit'@ androidla!el,@Astring/app_name@< >intent-filter< >a&tion androidname,@android.intent.a&tion.M)40@ /< >&ategor' androidname,@android.intent.&ategor'.B)C0=+D%@ /< >/intent-filter< >/a&tivit'< >/appli&ation<>/manifest<
This is the manifest file for the program.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@ < >7utton androidla'out_height,@wrap_&ontent@ androidla'out_width,@wrap_&ontent@ androidla'out_margin*op,@1dip@
androidtext,@Astring/!tnla!el@ androidon=li&k,@on=li&k@ /<>/BinearBa'out<
In the main.xml layout file, we define one button widget with the /uttonJ element. The first
two attributes define the si"e of the button so that it is big enough to show its content. The
android#laout_margin*op+,dip, creates a margin between the title bar of the screen and
the button widget. The dip 3density independent pixel4 is a unit of measurement that is used
for Android layout management. It best reflects the rich diversity of resolutions and densities
of various Android appliances. The android#text+,@string/btnlabel, attribute defines a text
for the button. The actual text resides in the strings.xml file, which we cover before long.
?inally, the android#on$lic"+,on$lic", attribute creates a button event listener for the clickevent. All we need to do is to define the on'lick34 method in the relevant #ava source file.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<:inish !utton>/string< >string name,@!tnla!el@<:inish>/string<>/resour&es<
In the strings.xml file we have two resource strings. The first is used in the manifest file to
provide a name for the application and the main activity. The second is used in the layout file
to provide a text label for the button widget.
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 10/77
2ainActivity.avapa&kage &om.zet&ode.finishE
import android.app.)&tivit'Eimport android.view.iewEimport android.os.7undleE
pu!li& &lass Main)&tivit' extends )&tivit'F AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.main6E I
pu!li& void on=li&k3iew view6F
finish36E
II
This is the source file for the main activity. 8e have defined an on=li&k36 method which
reacts to the button click events. It must take a (iew as its sole parameter. The method calls
the finish36 method which closes the current activity. 8e are redirected back to the list of
applications.
?igure@ /utton
'licking on the button we are redirected back to the list of applications.
Showing a toast
A toast is a view that contains a uick message for the user. Toasts can be displayed for ashort or a long period of time. In our second application we create a button widget. It will
show a toast message after being pressed.
Android2anifest.xml>?xml version,@1.@ en&oding,@utf-8@?<>manifest xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ pa&kage,@&om.zet&ode.toast@ androidversion=ode,@1@ androidversion0ame,@1.@< >appli&ation androidla!el,@Astring/app_name@
androidi&on,@Adrawa!le/i&_laun&her@< >a&tivit' androidname,@Main)&tivit'@ androidla!el,@Astring/app_name@< >intent-filter<
7%
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 11/77
>a&tion androidname,@android.intent.a&tion.M)40@ /< >&ategor'androidname,@android.intent.&ategor'.B)C0=+D%@ /< >/intent-filter< >/a&tivit'< >/appli&ation<
>/manifest<
This is the manifest file.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@ < >7utton
androidid,@AJid/!tn4d@ androidla'out_width,@wrap_&ontent@ androidla'out_height,@wrap_&ontent@ androidla'out_margin*op,@1dip@ androidtext,@Astring/la!el@ /<>/BinearBa'out<
In the main.xml layout file, we have one button widget inside the LinearLayout, which
arranges widgets in a single row or column. In our case the button is in a single column. The
button has a android#id+,@id/btn0d, attribute. The attribute supplies an identifier name for
the button. 8e will retrieve the button in the main activity using the findiew7'4d36
method. 8idgets that are not being referenced do not need this attribute. The plus sign is used
when we create the id of the element. *ubseuent references to the element in the E2L filewould be used without the plus sign. 3?or example in layout managers.4
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<"how *oast>/string< >string name,@la!el@<"how>/string<>/resour&es<
This is the strings.xml resource file. The button will have the F*howF text label.
2ainActivity.avapa&kage &om.zet&ode.toastE
import android.app.)&tivit'Eimport android.os.7undleEimport android.view.iewEimport android.view.iew.Hn=li&kBistenerEimport android.view.Kravit'Eimport android.widget.7uttonEimport android.widget.*oastEimport android.&ontent.=ontextE
pu!li& &lass Main)&tivit' extends )&tivit'F AHverride
77
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 12/77
pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.main6E
initC436E
I
pu!li& void initC436 F 7utton !tn , 37utton6 findiew7'4d3%.id.!tn4d6E
!tn.setHn=li&kBistener3new Hn=li&kBistener36F
AHverride pu!li& void on=li&k3iew arg6
F =ontext &tx , get)ppli&ation=ontext36E "tring msg , @7utton was &li&ked@E
int duration , *oast.BD0K*+_"+H%*E
*oast toast , *oast.make*ext3&txL msgL duration6E toast.setKravit'3Kravit'.=D0*D%L L 6E toast.show36E I I6E II
8hen we click on the button widget, it will show a Toast message in the center of the screen.
The toast will be displayed for a short period of time.
...import android.view.iew.Hn=li&kBistenerEimport android.view.Kravit'Eimport android.widget.7uttonEimport android.widget.*oastEimport android.&ontent.=ontextE
These are some of the new classes needed to be imported in this example.
initC436E
In the on=reate36 method we call the init<I34 method. It adds the Hn=li&kBistener36 tothe button widget.
7utton !tn , 37utton6 findiew7'4d3%.id.!tn4d6E
8e get the reference to the button widget that we have specified in the main.xml file. 8e use
the findiew7'4d36 method. The method finds a (iew 3A button is a kind of a !iew4 by the
id attribute from the main.xml file. The id is located in the auto-generated 6 class. 6 stands
for 6esource. 8e can have a look at the 6 source code in the gen0com0"etcode0toast06.ava
source file. There we will find the button id among others.
!tn.setHn=li&kBistener3new Hn=li&kBistener36F AHverride
7$
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 13/77
pu!li& void on=li&k3iew arg6F
... II6E
8e add the Hn=li&kBistener to the button widged. Listeners can be set up in various ways.ere we use an anonymous inner class.
=ontext &tx , get)ppli&ation=ontext36E"tring msg , @7utton was &li&ked@Eint duration , *oast.BD0K*+_"+H%*E
*oast toast , *oast.make*ext3&txL msgL duration6Etoast.setKravit'3Kravit'.=D0*D%L L 6Etoast.show36E
8e set up and show the Toast view. 8e get the application context, create a message and the
duration time. The gravity is the alignment of the view within its parent. 8e position the toastin the center of the screen. /y default, the toasts are displayed at the bottom of the screen.
?igure@ *howing toast
CheckBox
A 'heck/ox widget is a special kind of a button. It has two states. )n and off. The on state is
represented by a tick mark inside a rectangle.
ava.lang.H!e&t android.view.iew android.widget.*extiew android.widget.7utton android.widget.=ompound7utton android.widget.=he&k7ox
This is the inheritance hierarchy for the 'heck/ox widget. The /utton widget is among its
parents.
7&
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 14/77
Android2anifest.xml>?xml version,@1.@ en&oding,@utf-8@?<>manifest xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ pa&kage,@&om.zet&ode.&he&k!ox@ androidversion=ode,@1@ androidversion0ame,@1.@<
>appli&ation androidla!el,@Astring/app_name@androidi&on,@Adrawa!le/i&_laun&her@<
>a&tivit' androidname,@Main)&tivit'@ androidla!el,@Astring/app_name@< >intent-filter< >a&tion androidname,@android.intent.a&tion.M)40@ /< >&ategor'androidname,@android.intent.&ategor'.B)C0=+D%@ /< >/intent-filter< >/a&tivit'< >/appli&ation<>/manifest<
The manifest file.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@ < >=he&k7ox androidid,@AJid/&!_id@ androidla'out_width,@wrap_&ontent@
androidla'out_height,@wrap_&ontent@ androidtext,@Astring/&!la!el@ /<>/BinearBa'out<
The 'heck/oxJ element creates a 'heck/ox widget.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<=he&k7ox>/string< >string name,@&!la!el@<"how title>/string<>/resour&es<
*tring resources.
2ainActivity.avapa&kage &om.zet&ode.&he&k!oxE
import android.app.)&tivit'Eimport android.os.7undleEimport android.view.iewEimport android.view.iew.Hn=li&kBistenerEimport android.widget.=he&k7oxE
pu!li& &lass Main)&tivit' extends )&tivit'F private =he&k7ox &!E
7D
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 15/77
AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.main6E
initC436E I
pu!li& void initC436F
&! , 3=he&k7ox6 findiew7'4d3%.id.&!_id6E &!.set=he&ked3true6E
&!.setHn=li&kBistener3new Hn=li&kBistener36F
AHverride pu!li& void on=li&k3iew v6
F =he&k7ox &! , 3=he&k7ox6 vE
if 3&!.is=he&ked366F
set*itle3@=he&k7ox@6E I else F set*itle3@@6E I I I6E II
The 'heck/ox toggles the visibility of the screen title. 8hen the 'heck/ox is in a checked
state, the title is visible. )thervise it is not.
import android.widget.=he&k7oxE
8e import the 'heck/ox class into the source file.
&! , 3=he&k7ox6 findiew7'4d3%.id.&!_id6E
8e find the reference to the 'heck/ox widget, defined in the main.xml file.
&!.set=he&ked3true6E
The title is visible by default, so the 'heck/ox must be in a checked state. 8e use the
set=he&ked36 method to change the state of the widget.
&!.setHn=li&kBistener3new Hn=li&kBistener36F AHverride pu!li& void on=li&k3iew v6
F=he&k7ox &! , 3=he&k7ox6 vE
if 3&!.is=he&ked366F
7G
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 16/77
set*itle3@=he&k7ox@6E I else F set*itle3@@6E I II6E
In the Hn=li&kBistener36 we define the on=li&k36 method. 8e determine the state of the
widget using the is=he&ked36 method. The title of the screen is modified with the
set*itle36 method.
?igure@ 'heck/ox widget
In this chapter of the Android development tutorial we have presented button widgets.
Intents
In this chapter of the Android development tutorial, we will talk about Intents.
According to the Android developer documentation, an 0ntent is an asynchronous message. It
is an abstract description of an operation to be performed. Intents are used to navigate
through activities. Activities, services and broadcast receivers are activated through intents.Intents enable loose coupling of code in the application. An Intent is passed to the some
method like =ontext.start)&tivit'36 or =ontext.start"ervi&e36 to perform some
action.
There are two types of intents. 9xplicit and implicit. In explicit intents you provide the name
of the Activity class. In implicit intents, you tell the system what to do rather than name the
Activity class to launch.
Implicit Intent
isplaying a web page can be done via an implicit intent. It will start a default web browser
with the specified web page. In the example we will display the contents of a web page. The
manifest file is not modified.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@ androidorientation,@verti&al@ <
>7utton androidid,@AJid/!utton1@ androidla'out_width,@wrap_&ontent@
7H
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 17/77
androidla'out_height,@wrap_&ontent@ androidla'out_margin,@dp@ androidon=li&k,@on=li&ked@ androidtext,@Astring/!tn_title@ /< >/BinearBa'out<
In the main.xml layout file, we have ust a simple button widget. 'licking on the button will
show the web page.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<Crl>/string< >string name,@!tn_title@<isit>/string<>/resour&es<
*tring resources.
2ainActivity.avapa&kage &om.zet&ode.urlE
import android.app.)&tivit'Eimport android.os.7undleEimport android.&ontent.4ntentEimport android.net.CriEimport android.view.iewE
pu!li& &lass Main)&tivit' extends )&tivit'F
AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.main6E I
pu!li& void on=li&ked3iew view6 F 4ntent intent , new 4ntent34ntent.)=*4H0_4DNL
Cri.parse3@http//www.google.&om@66E start)&tivit'3intent6E
II
This is the 2ainActivity.ava source file.
pu!li& void on=li&ked3iew view6F 4ntent intent , new 4ntent34ntent.)=*4H0_4DNL
Cri.parse3@http//www.google.&om@66E start)&tivit'3intent6EI
In the on=li&ked36 method, we create an Intent obect and start a new activity. 8ith this
implicit intent, we tell Android to start a default web browser with google.com web pageopened.
7B
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 18/77
?igure@ 8eb page in Android emulator
Explicit intent In explicit intents, we provide the exact class to be run.
Android2anifest.xml>?xml version,@1.@ en&oding,@utf-8@?<>manifest xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ pa&kage,@&om.zet&ode.expli&it@ androidversion=ode,@1@ androidversion0ame,@1.@< >appli&ation androidla!el,@Astring/app_name@
androidi&on,@Adrawa!le/i&_laun&her@< >a&tivit' androidname,@Main)&tivit'@ androidla!el,@Astring/app_name@< >intent-filter< >a&tion androidname,@android.intent.a&tion.M)40@ /< >&ategor'androidname,@android.intent.&ategor'.B)C0=+D%@ /< >/intent-filter< >/a&tivit'<
>a&tivit' androidname,@.0ext)&tivit'@<>/a&tivit'<
>/appli&ation<>/manifest<
In the manifest file we register the new activity under the name 5extActivity. The leading dot
is a shorthand for the full package name, com."etcode.explicit in our case.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@ < >7utton androidid,@AJid/!utton1@ androidla'out_width,@wrap_&ontent@ androidla'out_height,@wrap_&ontent@
7K
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 19/77
androidla'out_margin,@dp@ androidon=li&k,@on=li&ked@ androidtext,@Astring/!tn_title@ /<>/BinearBa'out<
In the main.xml file we have one button. 'licking on this button will start a new explicit
activity.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<Dxpli&it>/string< >string name,@!tn_title@<0ext>/string<>/resour&es<
This is the strings.xml resource file.
$ ls sr&/&om/zet&ode/expli&it/Main)&tivit'.ava 0ext)&tivit'.ava
In the src0com0"etcode0explicit subdirectory we have two source files for two activities.
2ainActivity.avapa&kage &om.zet&ode.expli&itE
import android.app.)&tivit'Eimport android.os.7undleEimport android.view.iewEimport android.&ontent.4ntentE
pu!li& &lass Main)&tivit' extends )&tivit'F AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.main6E I
pu!li& void on=li&ked3iew view6 F 4ntent intent , new 4ntent3thisL 0ext)&tivit'.&lass6E start)&tivit'3intent6E
II
This is the source for the main activity. In the on'licked34 method, we start a new explicit
intent.
pu!li& void on=li&ked3iew view6F 4ntent intent , new 4ntent3thisL 0ext)&tivit'.&lass6E start)&tivit'3intent6EI
The second parameter of the Intent constructor is the class name to be invoked. The activityis started with the start)&tivit'36 method.
7
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 20/77
5extActivity.avapa&kage &om.zet&ode.expli&itE
import android.app.)&tivit'Eimport android.os.7undleEimport android.widget.*extiewE
import android.widget.BinearBa'outE
pu!li& &lass 0ext)&tivit' extends )&tivit'F AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E initC436E I
pu!li& void initC436 F
BinearBa'out la' , new BinearBa'out3this6E
*extiew tv , new *extiew3this6E tv.set*ext3@0ext s&reen@6E la'.addiew3tv6E
set=ontentiew3la'6E II
This is the 1extActivit.java source code. In this activity, we show a Text!iew on the screen.
It is programatically placed into a linear layout.
Transfering data
Intents are used to transfer data from one activity to another. 8e use the putDxtra36 method
to add extra data to an intent. In the following example, we write a name to the edit text and
click on the *end button. 8e will land on another screen where we will see a greeting to the
name, that we have entered.
$ ls res/la'out/s&reen1.xml s&reen2.xml$ ls sr&/&om/zet&ode/swit&h2/:irst"&reen.ava "e&ond"&reen.ava
In the res0layout directory we have two E2L layout files. In the src0com0"etcode0switch$ we
have source files of two activities.
Android2anifest.xml>?xml version,@1.@ en&oding,@utf-8@?<>manifest xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ pa&kage,@&om.zet&ode.swit&h2@ androidversion=ode,@1@ androidversion0ame,@1.@< >appli&ation androidla!el,@Astring/app_name@ androidi&on,@Adrawa!le/i&_laun&her@< >a&tivit' androidname,@.:irst"&reen@< >intent-filter<
$%
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 21/77
>a&tion androidname,@android.intent.a&tion.M)40@ /< >&ategor'androidname,@android.intent.&ategor'.B)C0=+D%@ /< >/intent-filter< >/a&tivit'<
>a&tivit' androidname,@."e&ond"&reen@<>/a&tivit'< >/appli&ation<
>/manifest<
In the manifest file we define two activities. The ?irst*creen and the *econd*creen activity.
The ?irst*creen is the main activity.
screen7.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@
androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@ < >Ddit*ext androidid,@AJid/edit4d@ androidla'out_width,@fill_parent@ androidla'out_height,@wrap_&ontent@ androidla'out_margin*op,@1dip@ androidla'out_margin7ottom,@1dip@ androidhint,@Astring/et+int@ /<
>7utton androidla'out_width,@wrap_&ontent@ androidla'out_height,@wrap_&ontent@
androidtext,@Astring/!tn_send@androidon=li&k,@sendMessage@ /<>/BinearBa'out<
The screen.xml layout file is loaded by the ?irst*creen activity. It displays an 9ditText and a
/utton widget. The android@hint attribute shows a default shaded text in the 9ditText.
screen$.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@
androidla'out_height,@fill_parent@ < >*extiew androidid,@AJid/tv4d@ androidla'out_width,@fill_parent@ androidla'out_height,@wrap_&ontent@ /<>/BinearBa'out<
In the screen2.xml file we have one Text!iew widget. It will display the text that we will
transfer from one screen to another. It is loaded by the *econd*creen activity.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es<
$7
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 22/77
>string name,@app_name@<"wit&h>/string< >string name,@et+int@<Dnter 'our name>/string< >string name,@!tn_send@<"end>/string<>/resour&es<
This is the strings.xml resource file.
?irst*creen.avapa&kage &om.zet&ode.swit&h2E
import android.app.)&tivit'Eimport android.os.7undleEimport android.&ontent.4ntentEimport android.view.iewEimport android.widget.Ddit*extE
pu!li& &lass :irst"&reen extends )&tivit'F
private Ddit*ext inameE AHverride
pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E
set*itle3@:irst s&reen@6E set=ontentiew3%.la'out.s&reen16E
iname , 3Ddit*ext6 findiew7'4d3%.id.edit4d6E I
pu!li& void sendMessage3iew view6F
4ntent swit&h*o , new 4ntent3thisL "e&ond"&reen.&lass6Eswit&h*o.putDxtra3@name@L iname.get*ext36.to"tring366Estart)&tivit'3swit&h*o6E
II
The ?irst*creen is the main activity. The sendMessage36 method is called, when we click on
the button.
pu!li& void sendMessage3iew view6F 4ntent swit&h*o , new 4ntent3thisL "e&ond"&reen.&lass6E
swit&h*o.putDxtra3@name@L iname.get*ext36.to"tring366Estart)&tivit'3swit&h*o6E
I
In the sendMessage36 method, we create an instance of an Intent. It will direct us to the
*econd*creen activity. 8ith the putDxtra36 method, we add data from the 9ditText to the
intent. The first parameter is the name by which we will refer the data. The second parameter
is the data to be transfered.
*econd*creen.ava
pa&kage &om.zet&ode.swit&h2E
import android.app.)&tivit'E
$$
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 23/77
import android.os.7undleEimport android.&ontent.4ntentEimport android.widget.*extiewE
pu!li& &lass "e&ond"&reen extends )&tivit'F
AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.s&reen26E
setupC436E I
void setupC436 F set*itle3@"e&ond s&reen@6E
*extiew tv , 3*extiew6 findiew7'4d3%.id.tv4d6E 4ntent i , get4ntent36E
"tring name , i.get"tringDxtra3@[email protected]*ext3@Oou have entered @ J name6E
II
This is the *econd*creen.ava source file. It is called by the ?irst*creen activity.
setupC436E
In the setup<I34 method, we set up the user interface of the screen.
set*itle3@"e&ond s&reen@6E
8e give the title to the screen with the set*itle36 method.
4ntent i , get4ntent36E"tring name , i.get"tringDxtra3@[email protected]*ext3@Oou have entered @ J name6E
The get4ntent36 method returns the intent that started the activity. 8e get the extra data
using the get"tringDxtra36 method. The data is set to the Text!iew.
In this chapter of the Android development tutorial, we have written about Intents.
Layout management
In this chapter of the Android development tutorial we will talk about layout management.
widgets.
8hen we design the user interface of our application, we decide what components we will
use and how we will organi"e those components in the application. To organi"e ourcomponents, we use speciali"ed non visible obects called layout managers.
$&
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 24/77
There are several layout managers in Android. A &inear&aout lines up its views in one row
or column. A !rame&aout is a simple layout manager used to display one view. A
3elative&aout is a layout manager in which the views are positioned in relation to each other
or to the parent. The most powerful layout manager is the 4rid&aout manager. It arranges
the views in a grid.
Showing an image with rame!a"out
The first example shows an image using the ?rameLayout manager.
$ ls res/drawa!le-hdpi/i&_laun&her.png zamok.pg
epending on a android virtual device we are using, we put the image in the corresponding
subdirectory of the res directory.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>:rameBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidla'out_gravit',@top@ androidla'out_width,@wrap_&ontent@ androidla'out_height,@wrap_&ontent@ < >4mageiew
androidla'out_height,@mat&h_parent@androidla'out_width,@mat&h_parent@androidsr&,@Adrawa!le/zamok@ /<
>/:rameBa'out<
In the ?rameLayout manager, we put one Image!iew.
>:rameBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidla'out_gravit',@top@ androidla'out_width,@wrap_&ontent@ androidla'out_height,@wrap_&ontent@ <
The :rameBa'out is big enough to display the 4mageiew by setting the layout width and
height to wrap_&ontent. It is pushed to the top using the la'out_gravit' attribute.
>4mageiewandroidla'out_height,@mat&h_parent@androidla'out_width,@mat&h_parent@androidsr&,@Adrawa!le/zamok@ /<
The 4mageiew displays an image. The image is located in a subdirectory of the res directory.
$D
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 25/77
?igure@ *howing an image with a ?rameLayout
A row of #uttons
In the example we create a row of four buttons.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@horizontal@ androidla'out_width,@mat&h_parent@
androidla'out_height,@mat&h_parent@ < >7utton
androidla'out_height,@wrap_&ontent@ androidla'out_width,@wrap_&ontent@ androidtext,@7utton1@ /<
>7utton androidla'out_height,@wrap_&ontent@ androidla'out_width,@wrap_&ontent@ androidtext,@7utton2@ /<
>7utton androidla'out_height,@wrap_&ontent@ androidla'out_width,@wrap_&ontent@ androidtext,@7utton@ /< >7utton
androidla'out_height,@wrap_&ontent@ androidla'out_width,@wrap_&ontent@ androidtext,@7utton@ /<
>/BinearBa'out<
8e have a hori"ontal BinearBa'out. In this layout, we add four buttons.
>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@
$G
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 26/77
androidorientation,@horizontal@ androidla'out_width,@mat&h_parent@ androidla'out_height,@mat&h_parent@ <
8e create a hori"ontal LinearLayout manager. The width and height of the layout match the
parent which means that it fills the entire screen.
>7utton androidla'out_height,@wrap_&ontent@ androidla'out_width,@wrap_&ontent@ androidtext,@7utton1@ /<
9ach of the four buttons use the wrap>content property. They are then ust big enough to
display their content.
?igure@ A row of buttons
A row of #uttons II
In the third example of this chapter, we show how to programatically create a row of buttonswith a LinearLayout manager.
2ainActivity.avapa&kage &om.zet&ode.!tnrow2E
import android.app.)&tivit'Eimport android.os.7undleEimport android.widget.7uttonEimport android.widget.BinearBa'outE
pu!li& &lass 7utton%ow2 extends )&tivit'F
AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E
initC436E I
pu!li& void initC436 F 7utton !tn1 , new 7utton3this6E !tn1.set*ext3@7utton@6E
7utton !tn2 , new 7utton3this6E !tn2.set*ext3@7utton@6E
$H
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 27/77
7utton !tn , new 7utton3this6E !tn.set*ext3@7utton@6E
7utton !tn , new 7utton3this6E !tn.set*ext3@7utton@6E
BinearBa'out ll , new BinearBa'out3this6E ll.setHrientation3BinearBa'out.+H%4PH0*)B6E
ll.addiew3!tn16E ll.addiew3!tn26E ll.addiew3!tn6E ll.addiew3!tn6E
set=ontentiew3ll6E II
?our buttons are placed in a hori"ontal LinearLayout. 8e will not use the layout E2L file inthis sample.
7utton !tn1 , new 7utton3this6E!tn1.set*ext3@7utton@6E
A 7utton widget is created. The text is set for the button with the set*ext36 method.
BinearBa'out ll , new BinearBa'out3this6Ell.setHrientation3BinearBa'out.+H%4PH0*)B6E
A hori"ontal BinearBa'out is created.
ll.addiew3!tn16Ell.addiew3!tn26Ell.addiew3!tn6Ell.addiew3!tn6E
/uttons are added to the layout manager.
set=ontentiew3ll6E
The linear layout manager is set to be the content view of the activity.
A column of #uttons
8e use the ?rameLayout and the LinearLayout managers to create a column of buttons
centered on the screen.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>:rameBa'out
xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@androidla'out_width,@wrap_&ontent@
androidla'out_height,@wrap_&ontent@ androidla'out_gravit',@&enter@<
$B
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 28/77
>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@
androidorientation,@verti&al@ androidla'out_width,@mat&h_parent@ androidla'out_height,@mat&h_parent@ <
>7utton androidla'out_height,@wrap_&ontent@ androidla'out_width,@wrap_&ontent@
androidtext,@7utton@ /<
>7utton androidla'out_height,@wrap_&ontent@ androidla'out_width,@wrap_&ontent@
androidtext,@7utton@ /<
>7utton androidla'out_height,@wrap_&ontent@
androidla'out_width,@wrap_&ontent@androidtext,@7utton@ /<
>7utton androidla'out_height,@wrap_&ontent@ androidla'out_width,@wrap_&ontent@
androidtext,@7utton@ /<
>/BinearBa'out<
>/:rameBa'out<
A LinearLayout manager with four buttons is placed in the ?rameLayout manager.
>:rameBa'outxmlnsandroid,@http//s&hemas.android.&om/apk/res/android@androidla'out_width,@wrap_&ontent@androidla'out_height,@wrap_&ontent@
androidla'out_gravit',@&enter@<
The ?rameLayout does not occupy all the available space. It is ust big enough to take all the
four buttons. And therefore we can use the la'out_gravit' attribute to center the
LinearLayout and its four buttons.
>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@mat&h_parent@ androidla'out_height,@mat&h_parent@ <
A vertical LinearLayout is created.
$K
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 29/77
?igure@ A column of buttons
Relati$e!a"out
6elativeLayout lets child views specify their position relative to the parent view or to each
other. The views are referenced by their ids.
main.xml
>?xml version,@1.@ en&oding,@utf-8@?<>%elativeBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@ <
>Ddit*ext androidid,@AJid/et4d@ androidla'out_margin*op,@1dp@
androidla'out_width,@mat&h_parent@ androidla'out_height,@wrap_&ontent@ /<
>7utton
androidid,@AJid/!tn_send4d@ androidla'out_!elow,@AJid/et4d@ androidla'out_width,@wrap_&ontent@
androidla'out_height,@wrap_&ontent@androidtext,@"end@ /<
>7utton androidid,@AJid/!tn_&lear4d@ androidla'out_!elow,@AJid/et4d@ androidla'out_to%ightHf,@AJid/!tn_send4d@ androidla'out_width,@wrap_&ontent@
androidla'out_height,@wrap_&ontent@androidtext,@=lear@ /<
>/%elativeBa'out<
$
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 30/77
The E2L code displays an 9ditText with two buttons.
>Ddit*ext androidid,@AJid/et4d@ androidla'out_margin*op,@1dp@
androidla'out_width,@mat&h_parent@
androidla'out_height,@wrap_&ontent@ /<
The Ddit*ext will be stretched from right to left by setting the androidla'out_width to
androidmat&h_parent . The widget will be high enough to show its contents. 8e specify
some gap between the widget and the border of the screen with androidla'out_margin*op
property.
>7utton androidid,@AJid/!tn_send4d@ androidla'out_!elow,@AJid/et4d@ androidla'out_width,@wrap_&ontent@
androidla'out_height,@wrap_&ontent@androidtext,@"end@ /<
The *end button widget will be placed below the 9ditText widget. To accomplish this, we
use the androidla'out_!elow property. 5ote that we reference the id of the widget that we
relate to.
>7utton androidid,@AJid/!tn_&lear4d@ androidla'out_!elow,@AJid/et4d@ androidla'out_to%ightHf,@AJid/!tn_send4d@ androidla'out_width,@wrap_&ontent@
androidla'out_height,@wrap_&ontent@androidtext,@=lear@ /<
The 'lear button is placed below the 9ditText widget and to the right of the *end button. 8e
accomplish this by two properties. The androidla'out_!elow and the
androidla'out_to%ightHf property.
?igure@ 6elativeLayout example
&%
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 31/77
%rid
A 4rid&aout manager places its children in a rectangular grid. The grid consists of row and
columns. The intersections of rows and columns are cells. 9ach cell is referenced by its
index. A view in a grid can occupy one or more cells. The gravit is a property that specifies
how a view should be placed in its group of cells.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>KridBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidla'out_width,@mat&h_parent@
androidla'out_height,@mat&h_parent@ <
>7utton androidtext,@3L 6@
androidla'out_row,@@
androidla'out_&olumn,@@ /<
>7utton androidla'out_row,@@
androidla'out_&olumn,@1@androidla'out_&olumn"pan,@2@
androidla'out_gravit',@fill_horizontal@ /<
>7utton androidtext,@3L 6@
androidla'out_row,@@androidla'out_&olumn,@@ /<
>7utton androidtext,@3L 6@androidla'out_row,@@androidla'out_&olumn,@@ /<
>7uttonandroidla'out_row,@1@
androidla'out_&olumn,@@ androidla'out_row"pan,@@
androidla'out_&olumn"pan,@@androidla'out_gravit',@fill@ /<
>7utton androidtext,@=enter@
androidla'out_row,@@ androidla'out_&olumn,@@ androidla'out_&olumn"pan,@@
androidla'out_gravit',@&enter_horizontal@ /<
>7utton androidtext,@%ight@
androidla'out_row,@@ androidla'out_&olumn,@@ androidla'out_&olumn"pan,@@
androidla'out_gravit',@right@ /<
>/KridBa'out<
&7
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 32/77
In the example we put a few buttons in a (ridLayout. 8e show how a button can stretch over
several cells.
>7utton androidtext,@3L 6@
androidla'out_row,@@androidla'out_&olumn,@@ /<
<sing the la'out_row and la'out_&olumn properties, we place a button at top-left cell. The
indeces start from "ero.
>7utton androidla'out_row,@@
androidla'out_&olumn,@1@androidla'out_&olumn"pan,@2@
androidla'out_gravit',@fill_horizontal@ /<
This button will span two columns. The la'out_gravit' property will cause the button tofill the two columns.
>7uttonandroidla'out_row,@1@
androidla'out_&olumn,@@ androidla'out_row"pan,@@
androidla'out_&olumn"pan,@@androidla'out_gravit',@fill@ /<
This button will span three rows and five columns.
>7utton androidtext,@=enter@
androidla'out_row,@@ androidla'out_&olumn,@@ androidla'out_&olumn"pan,@@
androidla'out_gravit',@&enter_horizontal@ /<
A view may not occupy all the space that was allotted to it. This button is hori"ontally
centered within five columns.
&$
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 33/77
?igure@ (ridLayout example
In this chapter of the Android development tutorial we worked with layout management.
'pinner widget
In this chapter of the Android development tutorial we will present a spinner widget.
A spinner widget enables a user to select an item from a list of options. In the normal state itshows the currently selected item. 'licking on the spinner widget shows a dropdown menu
with all available items. The user can choose a new one from the list. The "pinner class is
used to create a spinner widget.
The *pinner widget can be populated in the E2L file. )r it can be programatically filled. In
the latter case we need an Adapter class to populate the *pinner widget. An adapter is a
bridge between a *pinner and its data.
Spinner I
In the first example we have a *pinner widget whose items are defined in an E2L file.
Android2anifest.xml>?xml version,@1.@ en&oding,@utf-8@?<>manifest xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ pa&kage,@&om.zet&ode.finish@ androidversion=ode,@1@ androidversion0ame,@1.@< >appli&ation androidla!el,@Astring/app_name@androidi&on,@Adrawa!le/i&_laun&her@< >a&tivit' androidname,@Main)&tivit'@ androidla!el,@Astring/app_name@<
>intent-filter< >a&tion androidname,@android.intent.a&tion.M)40@ /<
&&
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 34/77
>&ategor' androidname,@android.intent.&ategor'.B)C0=+D%@ /< >/intent-filter< >/a&tivit'< >/appli&ation<>/manifest<
This is the manifest file for the program.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@ < >"pinner androidid,@AJid/spn@ androidla'out_width,@wrap_&ontent@
androidla'out_height,@wrap_&ontent@ androidentries,@Aarra'/dlangs@ androidla'out_margin*op,@1dip@ androidprompt,@Astring/spn_title@ /<
>*extiew androidid,@AJid/tv4d@ androidla'out_width,@fill_parent@ androidla'out_height,@wrap_&ontent@
androidla'out_margin*op,@1dip@ /<
>/BinearBa'out<
In the main.xml layout file, we have a *pinner and a Text!iew. The
android#entries+,@arra/dlangs, attribute defines a E2L resource that provides an array of
strings. The strings are written in the strings.xml file.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<"pinner>/string< >string name,@spn_title@<=hoose a language>/string<
>string-arra' name,@dlangs@<
>item<('thon>/item< >item<(+(>/item< >item<(erl>/item< >item<*&l>/item< >item<%u!'>/item< >/string-arra'<
>/resour&es<
In the strings.xml file we have the elements of the string array. These are displayed when we
click on the *pinner widget.
2ainActivity.avapa&kage &om.zet&ode.spinnerE
&D
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 35/77
import android.app.)&tivit'Eimport android.os.7undleEimport android.view.iewEimport android.widget.*extiewEimport android.widget."pinnerEimport android.widget.)dapteriewE
import android.widget.)dapteriew.Hn4tem"ele&tedBistenerE
pu!li& &lass Main)&tivit' extends )&tivit' implementsHn4tem"ele&tedBistenerF private *extiew tvE
AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.main6E
tv , 3*extiew6 findiew7'4d3%.id.tv4d6E
"pinner spn , 3"pinner6 findiew7'4d3%.id.spn6E spn.setHn4tem"ele&tedBistener3this6E I
AHverride pu!li& void on4tem"ele&ted3)dapteriew>?< parentL iew vL int posL longid6
F "tring item , parent.get4tem)t(osition3pos6.to"tring36E tv.set*ext3item6E
I
AHverride pu!li& void on0othing"ele&ted3)dapteriew>?< arg6
Ftv.set*ext3@@6E
II
The selected item from the *pinner widget is displayed in the Text!iew widget.
pu!li& &lass Main)&tivit' extends )&tivit' implementsHn4tem"ele&tedBistener
The 2ainActivity class implements the Hn4tem"ele&tedBistener . The class must now
implement two methods. The on4tem"ele&ted36 and on0othing"ele&ted36 methods.
"pinner spn , 3"pinner6 findiew7'4d3%.id.spn6Espn.setHn4tem"ele&tedBistener3this6E
These two lines get the reference to the *pinner widget and set the )nItem*electedListener
for it.
AHverride
pu!li& void on4tem"ele&ted3)dapteriew>?< parentL iew vL int posL long id6F
&G
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 36/77
"tring item , parent.get4tem)t(osition3pos6.to"tring36E tv.set*ext3item6EI
In the on4tem"ele&ted36 method we get the currently selected *pinner item with the
get4tem)t(osition36. The item is transformed to a string and set to the Text!iew.
?igure@ *pinner widget
Spinner II
In the second spinner example, we will define our list of spinner elements programatically.
?or this we will use the )rra')dapter in conunction with the )rra'Bist.
An Adapter design pattern is used by Android platform to work with the *pinner widget. The
)rra')dapter is an intermediary between the data source and the data view. In this case the
data source is the ArrayList and the view is the *pinner widget. <sing an adapter we are
decoupling our code.
Android2anifest.xml>?xml version,@1.@ en&oding,@utf-8@?<>manifest xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ pa&kage,@&om.zet&ode.toast@ androidversion=ode,@1@ androidversion0ame,@1.@< >appli&ation androidla!el,@Astring/app_name@
androidi&on,@Adrawa!le/i&_laun&her@< >a&tivit' androidname,@Main)&tivit'@ androidla!el,@Astring/app_name@< >intent-filter<
>a&tion androidname,@android.intent.a&tion.M)40@ /< >&ategor'androidname,@android.intent.&ategor'.B)C0=+D%@ /< >/intent-filter< >/a&tivit'< >/appli&ation<>/manifest<
This is the manifest file.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@
&H
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 37/77
androidla'out_height,@fill_parent@ < >"pinner
androidid,@AJid/spn4d@ androidla'out_width,@wrap_&ontent@
androidla'out_height,@wrap_&ontent@ androidla'out_margin*op,@1dip@androidprompt,@Astring/spn_title@ /<
>*extiew androidid,@AJid/tv4d@ androidla'out_width,@fill_parent@ androidla'out_height,@wrap_&ontent@ androidla'out_margin*op,@1dip@ /< >/BinearBa'out<
In the main.xml file we have two widgets. The *pinner and the Text!iew widget. This time
we do not define the array data entries for the *pinner.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<"pinner2>/string< >string name,@spn_title@<=hoose a language>/string<>/resour&es<
This is the strings.xml resource file.
2ainActivity.avapa&kage &om.zet&ode.spinner2E
import ava.util.)rra'BistEimport ava.util.BistE
import android.app.)&tivit'Eimport android.os.7undleEimport android.view.iewEimport android.widget."pinnerEimport android.widget.)rra')dapterEimport android.widget.*extiewEimport android.widget.)dapteriewEimport android.widget.)dapteriew.Hn4tem"ele&tedBistenerE
pu!li& &lass Main)&tivit' extends )&tivit' implementsHn4tem"ele&tedBistenerF private *extiew tvE private "pinner spnE
AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.main6E
setup36E
&B
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 38/77
I
pu!li& void setup36 F tv , 3*extiew6 findiew7'4d3%.id.tv4d6E
spn , 3"pinner6 findiew7'4d3%.id.spn4d6E fill"pinner3spn6E spn.setHn4tem"ele&tedBistener3this6E I
pu!li& void fill"pinner3"pinner spn6F
Bist>"tring< lst , new )rra'Bist>"tring<36E lst.add3@('thon@6E lst.add3@(+(@6E lst.add3@(erl@6E lst.add3@*&l@6E lst.add3@%u!'@6E
)rra')dapter>"tring< da , new )rra')dapter>"tring<3thisL android.%.la'out.simple_spinner_itemL lst6E da.set#rop#owniew%esour&e3android.%.la'out.simple_spinner_item6E
spn.set)dapter3da6E I
AHverride pu!li& void on4tem"ele&ted3)dapteriew>?< parentL iew vL int posL longid6
F "tring item , parent.get4tem)t(osition3pos6.to"tring36E
tv.set*ext3item6E I
AHverride pu!li& void on0othing"ele&ted3)dapteriew>?< arg6
Ftv.set*ext3@@6E
II
In the 2ainActivity.ava source file we fill the *pinner widget with data and implement the
)nItem*electedListener for the widget.
spn , 3"pinner6 findiew7'4d3%.id.spn4d6Efill"pinner3spn6E
8e get the reference to the "pinner widget and call the fill*pinner34 method to populate it
with data.
Bist>"tring< lst , new )rra'Bist>"tring<36Elst.add3@('[email protected]@(+(@6Elst.add3@([email protected]@*&[email protected]@%u!'@6E
An )rra'Bist is created and filled with strings.
&K
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 39/77
)rra')dapter>"tring< da , new )rra')dapter>"tring<3thisL android.%.la'out.simple_spinner_itemL lst6E
The instance of the )rra')dapter is created. It takes the ArrayList as a parameter.
da.set#rop#owniew%esour&e3android.%.la'out.simple_spinner_item6E
This line determines the look of the dropdown menu of the *pinner widget. This one is a
dropdown without radio buttons. A spinner with the
android.%.la'out.simple_spinner_dropdown_item defined has radio buttons in its rows.
spn.set)dapter3da6E
The adapter is set for the *pinner widget.
?igure@ *pinner dropdown menu
In this chapter of the Android development tutorial, we have written about a spinner widget.
'eek&ar widget
In this chapter of the Android development tutorial we will present the *eek/ar widget.
The *eek/ar widget is used to select a value from a range of values. The user drags a thumb
of the widget to select a specific value. To process the *eek/ar events, we implement the
5ee"6ar.%n5ee"6ar$hange&istener listener.
&
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 40/77
SeekBar example
8e have a *eek/ar widget and a Text!iew widget. The current value from the *eek/ar is
displayed in the Text!iew. Android manifest file is left untouched.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@ <>"eek7ar androidid,@AJid/s!4d@ androidla'out_width,@fill_parent@ androidla'out_height,@wrap_&ontent@ androidla'out_margin,@1dp@ androidmax,@1@
androidprogress,@@ /<>*extiew androidid,@AJid/tv4d@ androidla'out_width,@fill_parent@ androidla'out_height,@wrap_&ontent@ androidla'out_marginBeft,@1dp@ /<>/BinearBa'out<
In the main.xml layout file, we have two widgets defined. The *eek/ar widget and the
Text!iew widget.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<"eek7ar>/string< >string name,@init_tv_value@<>/string<>/resour&es<
This is strings.xml resource file. The init>tv>value is the initial value of the Text!iew widget.
2ainActivity.avapa&kage &om.zet&ode.seek!arE
import android.app.)&tivit'Eimport android.os.7undleEimport android.widget.*extiewEimport android.widget."eek7arEimport android.widget."eek7ar.Hn"eek7ar=hangeBistenerE
pu!li& &lass Main)&tivit' extends )&tivit' implementsHn"eek7ar=hangeBistener
F *extiew tvE
AHverride
pu!li& void on=reate37undle saved4nstan&e"tate6 F
D%
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 41/77
super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.main6E
"eek7ar s! , 3"eek7ar6 findiew7'4d3%.id.s!4d6E s!.setHn"eek7ar=hangeBistener3this6E
tv , 3*extiew6 findiew7'4d3%.id.tv4d6E "tring val , this.get"tring3%.string.init_tv_value6E tv.set*ext3val6E I
AHverride pu!li& void on(rogress=hanged3"eek7ar seek7arL int progressL !oolean fromCser6
F tv.set*ext3"tring.valueHf3progress66E I
AHverride
pu!li& void on"tart*ra&king*ou&h3"eek7ar seek7ar6F // not implemented
I
AHverride pu!li& void on"top*ra&king*ou&h3"eek7ar seek7ar6
F // not implemented
II
The current value from the *eek/ar is set to the Text!iew widget.
pu!li& &lass Main)&tivit' extends )&tivit' implementsHn"eek7ar=hangeBistener
The 2ainActivity class implements the )n*eek/ar'hangeListener. 8e neet to define three
abstract methods. The on+rogress'hanged34, the on*tartTrackingTouch34 and the
on*topTrackingTouch34 method. The last two methods are not implemented. They are related
to touch gestures. 8e provide only empty methods.
"eek7ar s! , 3"eek7ar6 findiew7'4d3%.id.s!4d6Es!.setHn"eek7ar=hangeBistener3this6E
8e get the reference to the *eek/ar widget and set a listener for it.
tv , 3*extiew6 findiew7'4d3%.id.tv4d6E"tring val , this.get"tring3%.string.init_tv_value6Etv.set*ext3val6E
8e get the reference to the Text!iew widget. 8e retrieve the init>tv>value from the string
resources and set it to the Text!iew.
AHverridepu!li& void on(rogress=hanged3"eek7ar seek7arL int progressL
!oolean fromCser6F
D7
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 42/77
tv.set*ext3"tring.valueHf3progress66EI
8hen we move the thumb of the *eek/ar, the on(rogress=hanged36 method is called. The
progress parameter is the current value of the *eek/ar. The default range is %..7%%. 8e set
the current value of the *eek/ar to the Text!iew widget.
?igure@ *eek/ar widget
In this chapter of the Android development tutorial, we have written about the *eek/arwidget.
Progress&ar widget
In this chapter of the Android development tutorial we will present the +rogress/ar widget. A
7rogress6ar is a widget that shows visually a progress of some task. The widget comes in
two basic modes. There is a circular bar and a hori"ontal bar.
8e will have two examples to demonstrate both of them.
&rogressBar I
8e have a hori"ontal +rogress/ar widget and a Text!iew widget, that shows the percentage
of the task completed. The manifest file is left untouched.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@
androidla'out_height,@fill_parent@ <>(rogress7ar
androidid,@AJid/p!4d@ androidla'out_width,@fill_parent@ androidla'out_height,@wrap_&ontent@ st'le,@?androidattr/progress7ar"t'le+orizontal@ androidla'out_margin,@1dp@ /<>*extiew androidid,@AJid/tv4d@ androidla'out_width,@fill_parent@ androidla'out_height,@wrap_&ontent@
androidla'out_margin,@1dp@ /<>/BinearBa'out<
D$
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 43/77
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 44/77
runHnCi*hread3new %unna!le36 Fpu!li& void run36 F
tv.set*ext3@:inished@6E I I6E
I +andler hnd , new +andler36
FAHverride
pu!li& void handleMessage3Message msg6F
prgJJE p!.set(rogress3prg6E
"tring per& , "tring.valueHf3prg6.to"tring36E tv.set*ext3per&J@Q &ompleted@6E I
IE IEI
8e create a thread to control the progress of a +rogress/ar.
new *hread3m'*hread6.start36E
A new thread is started. In Android, lengthy tasks should by performed inside a thread to
prevent the application from appearing unresponsive. A thread ends by returning from its
main34 method, or by an exception.
AHverridepu!li& void run36F while 3prg > 16 F tr' F hnd.sendMessage3hnd.o!tainMessage366E *hread.sleep316E I &at&h34nterruptedDx&eption e6
FBog.e3@D%%H%@L @*hread was 4nterrupted@6E
I I
runHnCi*hread3new %unna!le36 Fpu!li& void run36 F
tv.set*ext3@:inished@6E I I6EI
The code in a thread is placed in the run36 method. 8e will simulate a lengthy task by
calling the *hread.sleep36 method. This forces us to handle the 0nterrupted8xception.
Android application runs in a single-thread model. All components of the main activity are
DD
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 45/77
created in the main thread. These components cannot be manipulated in other threads. To
work around this, we use either the 9andler obect or call the runHnCi*hread36 method.
runHnCi*hread3new %unna!le36 Fpu!li& void run36 F
tv.set*ext3@:inished@6E II6E
)nly the original thread that created a view hierarchy can touch its views. ere we are
modifying the Text!iew widget. Therefore we have put the code into the runHnCi*hread36
method, which runs the code in the main, <I thread, where the widget was created.
+andler hnd , new +andler36F
AHverride pu!li& void handleMessage3Message msg6
F prgJJE p!.set(rogress3prg6E
"tring per& , "tring.valueHf3prg6.to"tring36E tv.set*ext3per&J@Q &ompleted@6E IIE
Another way to touch widgets from another thread is to use the 9andler obect. It is used to
enueue an action to be performed on a different thread than its own. 8e update the progress
bar and set a percentage of the task completed to the text view.
?igure@ +rogress/ar widget
&rogressBar II
In the second example, we show the usage of the +rogress/ar in a circular mode. The
manifest file does not need to be modified.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@
<>(rogress7arandroidid,@AJid/p!4d@
DG
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 46/77
androidla'out_width,@wrap_&ontent@ androidla'out_height,@wrap_&ontent@ /<>*extiew androidid,@AJid/tv4d@ androidla'out_width,@fill_parent@
androidla'out_height,@wrap_&ontent@ androidtext,@Astring/msg@ /<>/BinearBa'out<
In the main.xml file we have a +rogress/ar and a Text!iew. The +rogress/ar has the default
style, which is the circular style. This is the same as if we have used the stle+,:
android#attr/progress6ar5tle, attribute.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es<
>string name,@app_name@<=ir(rog7ar>/string< >string name,@msg@<(lease wait...>/string<>/resour&es<
8e have two string resources in the strings.xml file.
2ainActivity.avapa&kage &om.zet&ode.prog!arE
import android.app.)&tivit'Eimport android.os.7undleEimport android.os.+andlerE
import android.os.MessageEimport android.widget.(rogress7arEimport android.widget.*extiewEimport android.view.iewEimport android.util.BogE
pu!li& &lass Main)&tivit' extends )&tivit'F (rogress7ar p!E *extiew tvE int prg , E
AHverride
pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.main6E
p! , 3(rogress7ar6 findiew7'4d3%.id.p!4d6E tv , 3*extiew6 findiew7'4d3%.id.tv4d6E
new *hread3m'*hread6.start36E I
private %unna!le m'*hread , new %unna!le36 F
AHverride pu!li& void run36F
DH
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 47/77
while 3prg > 16 F tr' F hnd.sendMessage3hnd.o!tainMessage366E *hread.sleep316E
I &at&h34nterruptedDx&eption e6F
Bog.e3@D%%H%@L @*hread was 4nterrupted@6E I I
runHnCi*hread3new %unna!le36 Fpu!li& void run36 F
tv.set*ext3@:inished@6E p!.setisi!ilit'3iew.KH0D6E
I I6E
I +andler hnd , new +andler36
FAHverride
pu!li& void handleMessage3Message msg6F
prgJJE p!.set(rogress3prg6E I IE IEI
The code is similar to the first example with a few modifications.
runHnCi*hread3new %unna!le36 Fpu!li& void run36 F
tv.set*ext3@:inished@6E p!.setisi!ilit'3iew.KH0D6E
II6E
After the task was completed, we hide the +rogress/ar using the setisi!ilit'36 method.
The circle itself is an endless animation, so after the task was finished, we need to hide the
widget.
?igure@ 'ircular +rogress/ar widget
In this chapter of the Android development tutorial, we have mentioned +rogress/ar widget.
DB
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 48/77
Listiew widget
In this chapter of the Android development tutorial, we will explore the List!iew widget.
A &ist(iew is a widget that shows items in a verticall scrolling list. An Adapter obect is usedto fill the List!iew with data.
!istView widget I
In the example, we show a List!iew widget with the names of the planets of our solar
system. 8e use an ArrayAdapter to fill the List!iew with data.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@
androidorientation,@verti&al@androidla'out_width,@fill_parent@androidla'out_height,@fill_parent@<
>Bistiewandroidid,@AJid/lv4d@
androidla'out_width,@fill_parent@androidla'out_height,@fill_parent@ /<
>/BinearBa'out<
In the main.xml file we define one List!iew widget.
row.xml>?xml version,@1.@ en&oding,@utf-8@?<>*extiew xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@ androidpadding,@1dp@ androidtext"ize,@2sp@<>/*extiew<
In the row.xml file we define, how a list row will look like. 8e will have one Text!iew in
each row of a List!iew. The sp is a unit used for setting the font si"e.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<Bistiew>/string< >string-arra' name,@planets@< >item<Mer&ur'>/item< >item<enus>/item< >item<Darth>/item< >item<Mars>/item< >item<Rupiter>/item< >item<"aturn>/item< >item<Cranus>/item<
>item<0eptune>/item< >item<(luto>/item< >/string-arra'<
DK
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 49/77
>/resour&es<
The names of the planets are specified in the strings.xml file within a string array attribute.
2ainActivity.ava
pa&kage &om.zet&ode.listviewE
import android.app.)&tivit'Eimport android.os.7undleEimport android.widget.)rra')dapterEimport android.widget.BistiewE
pu!li& &lass Main)&tivit' extends )&tivit'F private Bistiew lvE
private )rra')dapter>"tring< laE
AHverride
pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.main6E
setupC436E I
pu!li& void setupC436 F
lv , 3Bistiew6 findiew7'4d3%.id.lv4d6E"tringST planets , get%esour&es36.get"tring)rra'3%.arra'.planets6Elv.set)dapter3new )rra')dapter>"tring<3thisL %.la'out.rowL
planets66E II
This is the 2ainActivity.ava source file.
lv , 3Bistiew6 findiew7'4d3%.id.lv4d6E
8e get the reference to the List!iew widget.
"tringST planets , get%esour&es36.get"tring)rra'3%.arra'.planets6E
This code line retrieves the names of the planets from the resource file.
lv.set)dapter3new )rra')dapter>"tring<3thisL %.la'out.rowL planets66E
An ArrayAdapter is created and set to the List!iew.
D
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 50/77
?igure@ List!iew widget
!istView widget II
A &istActivit is a special activity that holds a List!iew obect. List!iew is a common widget
and it typically takes the whole screen. Therefore a special activity was created. In the
example, the manifest file is not modified. 8e will also not need the main.xml layout file.
row.xml>?xml version,@1.@ en&oding,@utf-8@?<>*extiew xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidla'out_width,@fill_parent@
androidla'out_height,@fill_parent@ androidpadding,@1dp@ androidtext"ize,@2sp@<>/*extiew<
In the row.xml file we define one Text!iew in each row of a List!iew.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<Bistiew2>/string<>/resour&es<
This is the strings.xml resource file.
2ainActivity.avapa&kage &om.zet&ode.listview2E
import android.app.Bist)&tivit'Eimport android.os.7undleEimport android.view.iewEimport android.widget.)rra')dapterEimport android.widget.)dapteriewEimport android.widget.)dapteriew.Hn4tem=li&kBistenerE
import android.widget.)dapteriew.Hn4tem"ele&tedBistenerEimport android.widget.BistiewEimport android.widget.*extiewE
G%
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 51/77
pu!li& &lass Main)&tivit' extends Bist)&tivit'implements Hn4tem=li&kBistenerL Hn4tem"ele&tedBistener
FAHverride
pu!li& void on=reate37undle saved4nstan&e"tate6
F super.on=reate3saved4nstan&e"tate6E setupC436E I
pu!li& void setupC436 F
)rra')dapter>"tring< la , new )rra')dapter>"tring<3thisL%.la'out.row6E
la.add3@Mer&ur'@6E la.add3@enus@6E la.add3@Darth@6E la.add3@Mars@6E
la.add3@Rupiter@6E la.add3@"aturn@6E la.add3@Cranus@6E la.add3@0eptune@6E la.add3@(luto@6E
setBist)dapter3la6E
Bistiew lv , getBistiew36E lv.setHn4tem=li&kBistener3this6E lv.setHn4tem"ele&tedBistener3this6E I
pu!li& void on4tem=li&k3)dapteriew>?< parentL iew viewL int positionL long id6F
"tring planet , 33*extiew6 view6.get*ext36.to"tring36E set*itle3planet6E I
pu!li& void on4tem"ele&ted3)dapteriew>?< parentL iew viewL int positionL long id6
F"tring planet , 33*extiew6 view6.get*ext36.to"tring36E
set*itle3planet6E I
pu!li& void on0othing"ele&ted3)dapteriew>?< parent6F
// not implemented II
8e programatically create the items of the List!iew. 8e react to click and select events of
the List!iew. The planet that we select or click on will be shown in the titlebar.
pu!li& &lass Main)&tivit' extends Bist)&tivit'implements Hn4tem=li&kBistenerL Hn4tem"ele&tedBistener
G7
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 52/77
The 2ainActivity extends the Bist)&tivit' and implements two listeners. /y
implementing these two listeners, we must implement three abstract methods that are
associated with these listeners.
AHverride
pu!li& void on=reate37undle saved4nstan&e"tate6F super.on=reate3saved4nstan&e"tate6E setupC436EI
In the on'reate34 method we do not call the set'ontent!iew34 method. The List!iew widget
of the ListActivity will take up the whole screen.
)rra')dapter>"tring< la , new )rra')dapter>"tring<3thisL %.la'out.row6Ela.add3@Mer&ur'@6Ela.add3@[email protected]@Darth@6E...
8e create an instance of the )rra')dapter. 8e add names of the planets to the adapter.
setBist)dapter3la6E
*ets the adapter for the associated List!iew obect.
Bistiew lv , getBistiew36Elv.setHn4tem=li&kBistener3this6Elv.setHn4tem"ele&tedBistener3this6E
?rom the ListActivity we get the List!iew widget. The two listeners are set for the List!iew
widget.
pu!li& void on4tem=li&k3)dapteriew>?< parentL iew viewL int positionL long id6F
"tring planet , 33*extiew6 view6.get*ext36.to"tring36E set*itle3planet6EI
Implementing the Hn4tem=li&kBistener, we have to define the on4tem=li&k36 method.
8e get the planet name from the *extiew of the clicked row and set it to the titlebar.
pu!li& void on4tem"ele&ted3)dapteriew>?< parentL iew viewL int positionL long id6F
"tring planet , 33*extiew6 view6.get*ext36.to"tring36E set*itle3planet6EI
pu!li& void on0othing"ele&ted3)dapteriew>?< parent6F
// not implementedI
G$
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 53/77
After implementing the Hn4tem"ele&tedBistener we have to define two abstract methods.
The first method sets the currently selected planet to the titlebar. The second method is not
implemented.
?igure@ *elected row of a List!iew widget
In this chapter of the Android development tutorial, we have mentioned the List!iew widget.
Pickers
In this chapter of the Android development tutorial we will talk about android +ickers.+ickers are widgets that enable us to select a single value from a set of values.
There are number, date or time pickers.
'um#er&icker
1umber7ic"er is a widget that allows us to select a number from a predefined range of
values. The manifest file is not modified in this example.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@ <
>0um!er(i&ker androidid,@AJid/np4d@ androidla'out_margin*op,@dp@ androidla'out_width,@wrap_&ontent@ androidla'out_height,@wrap_&ontent@ /<
>*extiew
androidid,@AJid/tv4d@ androidla'out_width,@wrap_&ontent@
G&
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 54/77
androidla'out_height,@wrap_&ontent@ androidla'out_margin*op,@dp@
androidla'out_marginBeft,@dp@ androidtext,@@ androidtext"ize,@sp@ /<
>/BinearBa'out<
In the layout file we have a 5umber+icker widget and a Text!iew widget. The Text!iew
widget will display the selected value of the 5umber+icker.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<0um!er(i&ker>/string<>/resour&es<
The strings resource file.
2ainActivity.avapa&kage &om.zet&ode.numpi&kE
import android.app.)&tivit'Eimport android.os.7undleEimport android.widget.0um!er(i&kerEimport android.widget.*extiewEimport android.widget.0um!er(i&ker.Hnalue=hangeBistenerE
pu!li& &lass Main)&tivit' extends )&tivit'F
private *extiew tvE
AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.main6E
setupC436E I
pu!li& void setupC436 F tv , 3*extiew6 findiew7'4d3%.id.tv4d6E
0um!er(i&ker np , 30um!er(i&ker6 findiew7'4d3%.id.np4d6E
np.setHnalue=hangedBistener3new Hnalue=hangeBistener36 F pu!li& void onalue=hange30um!er(i&ker pi&kerL int oldalL
int newal6 F tv.set*ext3"tring.valueHf3newal66E
II6E
np.setMaxalue316E np.setMinalue36E I
GD
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 55/77
I
'licking on the plus and minus signs of the 5umber+icker we select a new value. The
currently selected value is displayed in the Text!iew widget.
0um!er(i&ker np , 30um!er(i&ker6 findiew7'4d3%.id.np4d6E
A reference to the 0um!er(i&ker widget is retrieved from the main.xml file.
np.setHnalue=hangedBistener3new Hnalue=hangeBistener36F pu!li& void onalue=hange30um!er(i&ker pi&kerL int oldalL
int newal6 F tv.set*ext3"tring.valueHf3newal66E
II6E
A Hnalue=hangeBistener is added to the 5umber+icker widget. It will call the
onalue=hange36 method when the value of the 5umber+icker is changed. Inside this
method, we set the currently selected value to the Text!iew widget.
np.setMaxalue316Enp.setMinalue36E
8e set the maximum and minimum value for the 5umber+icker.
?igure@ 5umber+icker widget
Time&icker
A *ime7ic"er is a widget for selecting the time of day. It has two modes, $D hour or A20+2
mode. *election of the hour and minute digit can be conrolled by vertical spinners. A
;ate7ic"er is a widget for selecting a date. It is very similar to the Time+icker.
The manifest file is not modified.
GG
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 56/77
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@
<
>*ime(i&ker androidid,@AJid/tp4d@ androidla'out_margin*op,@dp@ androidla'out_width,@wrap_&ontent@ androidla'out_height,@wrap_&ontent@ /<
>*extiew androidid,@AJid/tv4d@ androidla'out_width,@wrap_&ontent@ androidla'out_height,@wrap_&ontent@ androidla'out_margin*op,@dp@
androidla'out_marginBeft,@dp@
androidtext"ize,@sp@ /<
>/BinearBa'out<
In the main.xml file we have a Time+icker and Text!iew widgets. The selected time is
displayed in the Text!iew.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<*ime(i&ker>/string<>/resour&es<
This is the strings.xml resource file.
2ainActivity.avapa&kage &om.zet&ode.timepi&kerE
import android.app.)&tivit'Eimport android.os.7undleEimport android.widget.*ime(i&kerEimport android.widget.*extiewEimport android.widget.*ime(i&ker.Hn*ime=hangedBistenerE
pu!li& &lass Main)&tivit' extends )&tivit'F private *extiew tvE
AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.main6E
setupC436E I
pu!li& void setupC436 F tv , 3*extiew6 findiew7'4d3%.id.tv4d6E
GH
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 57/77
*ime(i&ker tp , 3*ime(i&ker6 findiew7'4d3%.id.tp4d6E displa'=urrent*ime3tp6E
tp.setHn*ime=hangedBistener3new Hn*ime=hangedBistener36 F
pu!li& void on*ime=hanged3*ime(i&ker viewL int hourHf#a'Lint minute6 F "tring7uilder tm , new "tring7uilder36E tm.append3hourHf#a'6E tm.append3@ h @6E
tm.append3minute6E tm.append3@ m@6E tv.set*ext3tm6E
II6E
I
pu!li& void displa'=urrent*ime3*ime(i&ker tp6 F int h , tp.get=urrent+our36E int m , tp.get=urrentMinute36E
"tring7uilder tm , new "tring7uilder36E tm.append3h6E tm.append3@ h @6E
tm.append3m6E tm.append3@ m@6E tv.set*ext3tm6E
II
The Time+icker listens to the Hn*ime=hangedBistener . 8hen the time is changed, the new
time value is set to the Text!iew inside the on*ime=hanged36 method.
tp.setHn*ime=hangedBistener3new Hn*ime=hangedBistener36F pu!li& void on*ime=hanged3*ime(i&ker viewL int hourHf#a'L
int minute6 F "tring7uilder tm , new "tring7uilder36E tm.append3hourHf#a'6E tm.append3@ h @6E
tm.append3minute6E tm.append3@ m@6E tv.set*ext3tm6E
II6E
Inside an anonymous Hn*ime=hangedBistener class we implement the on*ime=hanged36
method. 8ith the *tring/uilder we build the string to be displayed and set it to the Text!iew
widget.
pu!li& void displa'=urrent*ime3*ime(i&ker tp6F int h , tp.get=urrent+our36E int m , tp.get=urrentMinute36E
GB
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 58/77
"tring7uilder tm , new "tring7uilder36E tm.append3h6E tm.append3@ h @6E
tm.append3m6E tm.append3@ m@6E tv.set*ext3tm6E
I
8hen the activity is first shown, we display the current time.
?igure@ Time+icker widget
In this chapter of the Android development tutorial, we have written about +ickers.
(enus
In this chapter of the Android development tutorial we will work with menus. 2enus group
available commands of an application. In traditional desktop applications menus are part of a
menubar which is located mostly in the top area of the application. 'ontext or popup menus
are special cases of menus.
There are three kinds of menus in Android. )ptions menu, context menu and popup menu.
The options menu is the primary collection of menu items for an activity. In the options
menu we should have commands that have global impact on the applications. ?or example a
*ettings menu. It is displayed either at the top or at the bottom of the activity. The context
menu shows menu items in a specific context. ?or example for List!iew items. It is shown
when the user performs a long-click on an element. A popup menu displays a list of items in
a vertical list thatFs anchored to the view that invoked the menu. It appears below the anchor
view if there is room, or above the view otherwise. It should relate to regions of content in the
activity.
2enus can be created manually by coding or they can be defined in an E2L file. If we
define our menus in an E2L file we use the Menu0nflater obect to create menus from theE2L file.
GK
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 59/77
(ptions menu
)ur options menu will have two menu items. 8hen we select a menu item a Toast window is
shown with the name of the selected menu item. The options menu is displayed after we click
on the menu button.
The manifest file is not modified in this example.
?igure@ 2enu button
main.xml>?xml version,@1.@ en&oding,@utf-8@?<
>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@ < >*extiew
androidla'out_width,@fill_parent@ androidla'out_height,@wrap_&ontent@ androidtext,@Astring/message@ /< >/BinearBa'out<
In the main.xml layout file, we have one Text!iew widget. It will display a welcomemessage.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<HptionsMenu>/string< >string name,@message@<#emonstrating Hptions Menu>/string< >string name,@om1@<"ettings>/string< >string name,@om2@<*ools>/string<>/resour&es<
This is strings.xml file.
options>menu.xml>?xml version,@1.@ en&oding,@utf-8@?<>menu xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@< >item androidid,@AJid/settings@ androidtitle,@Astring/om1@ /< >item androidid,@AJid/tools@ androidtitle,@Astring/om2@ /<>/menu<
This is options_menu.xml file. It defines two menu items. The file is located in the res0menu0
subdirectory.
G
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 60/77
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 61/77
Inside the on=reateHptionsMenu36 method, we build the options menu from the
options>menu.xml file. 8e use the Menu4nflater class to do the ob.
AHverridepu!li& !oolean onHptions4tem"ele&ted3Menu4tem item6F...I
The onHptions4tem"ele&ted36 method handles the click events on the menu items.
&ase %.id.settings *oast.make*ext3Main)&tivit'.thisL @"ettings menu sele&ted.@L
*oast.BD0K*+_"+H%*6.show36E return trueE
In case of the selection of the *ettings menu item we show a Toast window with C*ettings
menu selectedC message.
?igure@ )ptions menu at the bottom of the activity
Context menu
8e have a List!iew with the names of our planets. A long-click on an element will show a
context menu with tree options. elete, <ppercase and Lowercase.
The manifest file is not modified.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@ <
H7
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 62/77
>Bistiewandroidid,@AJid/lv4d@
androidla'out_width,@fill_parent@androidla'out_height,@fill_parent@ /<
>/BinearBa'out<
This is main.xml file. It contais a List!iew widget.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<=ontextMenu>/string< >string-arra' name,@planets@< >item<Mer&ur'>/item< >item<enus>/item< >item<Darth>/item<
>item<Mars>/item< >item<Rupiter>/item< >item<"aturn>/item< >item<Cranus>/item< >item<0eptune>/item< >item<(luto>/item< >/string-arra'<>/resour&es<
This is the strings.xml resource file.
row.xml>?xml version,@1.@ en&oding,@utf-8@?<>*extiew xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@ androidpadding,@1dp@ androidtext"ize,@2sp@<>/*extiew<
This is the row.xml resource file. 9ach row of a List!iew consists of a single Text!iew.
2ainActivity.avapa&kage &om.zet&ode.&onmenuE
import android.app.)&tivit'Eimport android.os.7undleEimport android.widget.)rra')dapterEimport android.widget.BistiewEimport android.view.iewEimport android.view.MenuEimport android.view.Menu4nflaterEimport android.view.Menu4temEimport android.view.=ontextMenuEimport android.view.=ontextMenu.=ontextMenu4nfoEimport android.widget.)dapteriew.)dapter=ontextMenu4nfoE
import ava.util.)rra'sE
import ava.util.)rra'BistE
H$
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 63/77
pu!li& &lass Main)&tivit' extends )&tivit'F private Bistiew lvE
private )rra')dapter>"tring< laE
AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.main6E
setupC436E I
pu!li& void setupC436 F
lv , 3Bistiew6 findiew7'4d3%.id.lv4d6E"tringST planets , get%esour&es36.get"tring)rra'3%.arra'.planets6E
)rra'Bist>"tring< lst , new )rra'Bist>"tring<36E lst.add)ll3)rra's.asBist3planets66E
la , new )rra')dapter>"tring<3thisL %.la'out.rowL lst6E lv.set)dapter3la6E register:or=ontextMenu3lv6E I
AHverride pu!li& void on=reate=ontextMenu3=ontextMenu menuL iew vL
=ontextMenu4nfo menu4nfo6F
super.on=reate=ontextMenu3menuL vL menu4nfo6E
Menu4nflater inflater , getMenu4nflater36E inflater.inflate3%.menu.&ontext_menuL menu6E I
AHverride pu!li& !oolean on=ontext4tem"ele&ted3Menu4tem item6
F )dapter=ontextMenu4nfo info , 3)dapter=ontextMenu4nfo6item.getMenu4nfo36E
int pos , info.positionE "tring i , la.get4tem3pos6E
swit&h 3item.get4tem4d366F
&ase %.id.del4d la.remove3i6E return trueE
&ase %.id.up4d"tring upln , i.toCpper=ase36E
la.remove3i6E la.insert3uplnL pos6E
return trueE
&ase %.id.lo4d "tring lpln , i.toBower=ase36E la.remove3i6E la.insert3lplnL pos6E
H&
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 64/77
return trueE
default return super.on=ontext4tem"ele&ted3item6E I I
I
In order to implement the context menu, we have to override the on=reate=ontextMenu36
and the on=ontext4tem"ele&ted36 methods. 8e also need to call the
register:or=ontextMenu36 method for a specific view.
"tringST planets , get%esour&es36.get"tring)rra'3%.arra'.planets6E)rra'Bist>"tring< lst , new )rra'Bist>"tring<36Elst.add)ll3)rra's.asBist3planets66E
8e will be deleting items of the List!iew. Therefore, we need to use an ArrayList. )therwise
the list would be read-only.
register:or=ontextMenu3lv6E
The context menu is registered for the List!iew widget.
AHverridepu!li& void on=reate=ontextMenu3=ontextMenu menuL iew vL
=ontextMenu4nfo menu4nfo6F super.on=reate=ontextMenu3menuL vL menu4nfo6E Menu4nflater inflater , getMenu4nflater36E inflater.inflate3%.menu.&ontext_menuL menu6EI
In the on=reate=ontextMenu36 method we build the context menu from the
context>menu.xml file.
AHverridepu!li& !oolean on=ontext4tem"ele&ted3Menu4tem item6F...I
The on=ontext4tem"ele&ted36 reacts to list item selection events.
)dapter=ontextMenu4nfo info , 3)dapter=ontextMenu4nfo6 item.getMenu4nfo36E
int pos , info.positionE"tring i , la.get4tem3pos6E
To find out more about the selected item, we use the )dapter=ontextMenu4nfo class. 8e
get the position and the text of the selected item.
&ase %.id.del4d la.remove3i6E
return trueE
HD
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 65/77
If we select the elete context menu option, we remove the item from the ArrayAdapter.
&ase %.id.up4d"tring upln , i.toCpper=ase36E
la.remove3i6E la.insert3uplnL pos6E
return trueE
?or the <ppercase option, we modify the string, remove the original one and insert a new
one.
?igure@ 'ontext menu with three options
&opup menu
The example shows a +opup2enu after clicking on a button.
The manifest file is not modified.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<
>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@ < >7utton
androidid,@AJid/!tn4d@ androidla'out_height,@wrap_&ontent@ androidla'out_width,@wrap_&ontent@ androidla'out_margin*op,@1dip@ androidtext,@Astring/!tn_la!el@ androidon=li&k,@on=li&k@ /<
>*extiew
HG
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 66/77
androidid,@AJid/tv4d@ androidla'out_width,@fill_parent@ androidla'out_height,@wrap_&ontent@
androidla'out_margin*op,@1dip@ /< >/BinearBa'out<
This is main.xml file. 8e have a /utton widget and a Text!iew widget. The button will show
a +opup2enu.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<(opupMenu>/string< >string name,@!tn_la!el@<"how menu>/string< >string name,@pm1@<4tem 1>/string< >string name,@pm2@<4tem 2>/string<>/resour&es<
This is the strings.xml resource file.
popup>menu.xml>?xml version,@1.@ en&oding,@utf-8@?<>menu xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@< >item androidid,@AJid/settings@ androidtitle,@Astring/pm1@ /< >item androidid,@AJid/tools@ androidtitle,@Astring/pm2@ /<>/menu<
This is popup_menu.xml file. It defines two menu items. The file is located in the res0menu0subdirectory.
2ainActivity.avapa&kage &om.zet&ode.popmenuE
import android.app.)&tivit'Eimport android.os.7undleEimport android.view.iewEimport android.view.Menu4temEimport android.widget.*extiewEimport android.widget.(opupMenuE
import android.widget.(opupMenu.HnMenu4tem=li&kBistenerE
pu!li& &lass Main)&tivit' extends )&tivit' implements HnMenu4tem=li&kBistenerF
private *extiew tvE
AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.main6E
tv , 3*extiew6 findiew7'4d3%.id.tv4d6EI
HH
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 67/77
pu!li& void on=li&k3iew v6F
show(opupMenu3v6E I
pu!li& void show(opupMenu3iew v6
F (opupMenu pm , new (opupMenu3Main)&tivit'.thisL v6E pm.getMenu4nflater36.inflate3%.menu.popup_menuL pm.getMenu366E
pm.setHnMenu4tem=li&kBistener3this6Epm.show36E
I
AHverride pu!li& !oolean onMenu4tem=li&k3Menu4tem item6
Ftv.set*ext3item.to"tring36 J @ sele&ted@6E
return trueEI
I
A +opup2enu is displayed after clicking on the button widget.
pu!li& void on=li&k3iew v6F
show(opupMenu3v6EI
This method is a callback to the button click. The relation is set in the main.xml file via an
attribute. The method calls the show+opup2enu34 method.
pu!li& void show(opupMenu3iew v6F (opupMenu pm , new (opupMenu3Main)&tivit'.thisL v6E pm.getMenu4nflater36.inflate3%.menu.popup_menuL pm.getMenu366E
pm.setHnMenu4tem=li&kBistener3this6Epm.show36E
I
8e create an instance of the (opupMenu class. It builds the menu, sets the
HnMenu4tem=li&kBistener and shows the (opupMenu.
AHverride
pu!li& !oolean onMenu4tem=li&k3Menu4tem item6F
tv.set*ext3item.to"tring36 J @ sele&ted@6E return trueEI
After selecting a menu item the onMenu4tem=li&k36 method is called. It sets the itemFs title
to the Text!iew widget.
In this chapter of the Android development tutorial, we have worked with menus.
"ialogs
HB
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 68/77
In this chapter of the Android development tutorial we will talk about dialogs. 8e will
discuss the Android Alertialog.
A dialog is defined as a conversation between two or more persons. In a computer application
a dialog is a window which is used to CtalkC to the application. A dialog is used to input data,
modify data, change the application settings etc.
An Alert;ialog is a dialog used to display information or receive data. It can display one, two
or three buttons. It is created with a /uilder subclass.
Displa"ing a message
8e will use the Alertialog to display a message. In the example, we do not need to modify
the manifest file.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@ <
>7utton androidla'out_width,@wrap_&ontent@ androidla'out_height,@wrap_&ontent@ androidla'out_margin*op,@1dip@ androidon=li&k,@on=li&ked@ androidtext,@Astring/!tn_la!el@ /< >/BinearBa'out<
In the main.xml layout file, we have a /utton widget. This button will display an Alertialog.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<#ispla'"ize>/string< >string name,@!tn_la!el@<"how>/string<>/resour&es<
This is strings.xml file.
2ainActivity.avapa&kage &om.zet&ode.displa'sizeE
import android.app.)&tivit'Eimport android.os.7undleEimport android.view.iewEimport android.graphi&s.(ointEimport android.app.)lert#ialogEimport android.&ontent.#ialog4nterfa&eEimport android.view.NindowManagerE
import android.view.#ispla'E
HK
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 69/77
pu!li& &lass Main)&tivit' extends )&tivit'F
AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E
set=ontentiew3%.la'out.main6E I
pu!li& void on=li&ked3iew view6 F (oint p , get#ispla'"ize36E
)lert#ialog ad , new )lert#ialog.7uilder3this6.&reate36E
ad.set*itle3@#ispla' size@6E "tring msg , "tring.format3@NidthQdL +eightQd@L p.xL p.'6E ad.setMessage3msg6E ad.set4&on3android.%.drawa!le.i&_dialog_info6E
ad.set7utton3@H@L new #ialog4nterfa&e.Hn=li&kBistener36 F pu!li& void on=li&k3#ialog4nterfa&e dialogL int whi&h6 F dialog.&an&el36E I I6E
ad.show36EI
pu!li& (oint get#ispla'"ize36 F NindowManager wm , 3NindowManager6
get"'stem"ervi&e3N40#HN_"D%4=D6E #ispla' ds , wm.get#efault#ispla'36E
(oint p , new (oint36E ds.get"ize3p6E
return pE II
8e use the Alertialog to display the si"e of the display.
(oint p , get#ispla'"ize36E
In the custom getisplay*i"e34 method, we determine the si"e of the display.
)lert#ialog ad , new )lert#ialog.7uilder3this6.&reate36E
An instance of the )lert#ialog is created.
ad.set*itle3@#ispla' size@6E"tring msg , "tring.format3@NidthQdL +eightQd@L p.xL p.'6Ead.setMessage3msg6Ead.set4&on3android.%.drawa!le.i&_dialog_info6E
8e set a title, message and an icon for the dialog.
H
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 70/77
ad.set7utton3@H@L new #ialog4nterfa&e.Hn=li&kBistener36 F pu!li& void on=li&k3#ialog4nterfa&e dialogL int whi&h6 F dialog.&an&el36E II6E
8e add a button to the dialog. 8hen we click on the )= button, the dialog is closed.
ad.show36E
The show36 method shows the dialog.
NindowManager wm , 3NindowManager6 get"'stem"ervi&e3N40#HN_"D%4=D6E#ispla' ds , wm.get#efault#ispla'36E
8e get the default display.
(oint p , new (oint36Eds.get"ize3p6E
8e find out the si"e of the display with the get"ize36 method.
?igure@ Alertialog showing the si"e of the display
Recei$ing data
The second example uses the Alertialog to receive data from a user. The dialog will ask a
user for his name. It will then display the input in a Text!iew widget.
The manifest file is not modified.
B%
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 71/77
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@
<
>7utton androidid,@AJid/!tn4d@ androidla'out_width,@wrap_&ontent@ androidla'out_height,@wrap_&ontent@ androidla'out_margin*op,@1dip@ androidon=li&k,@on=li&ked@ androidtext,@Astring/!tn_la!el@ /<
>*extiew androidid,@AJid/tv4d@ androidla'out_width,@fill_parent@
androidla'out_height,@wrap_&ontent@ /< >/BinearBa'out<
This is main.xml file. 8e have a /utton widget and a Text!iew widget. The button will show
the dialog window. The Text!iew will receive the input text from the dialog.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<4nput#ialog>/string< >string name,@!tn_la!el@<"how dialog>/string<
>/resour&es<
This is the strings.xml resource file.
2ainActivity.avapa&kage &om.zet&ode.inputE
import android.app.)&tivit'Eimport android.os.7undleEimport android.app.)lert#ialogEimport android.view.iewEimport android.widget.Ddit*extE
import android.widget.*extiewEimport android.&ontent.#ialog4nterfa&eE
pu!li& &lass Main)&tivit' extends )&tivit'F private *extiew tvE
AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.main6E
tv , 3*extiew6 findiew7'4d3%.id.tv4d6E I
B7
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 72/77
pu!li& void on=li&ked3iew view6 F )lert#ialog.7uilder ad , new )lert#ialog.7uilder3this6E
ad.set*itle3@4nput@6E ad.setMessage3@Dnter 'our name@6E
final Ddit*ext input , new Ddit*ext3this6E ad.setiew3input6E
ad.set(ositive7utton3@Hk@L new #ialog4nterfa&e.Hn=li&kBistener36 F pu!li& void on=li&k3#ialog4nterfa&e dlgL int whi&h6 F "tring val , input.get*ext36.to"tring36E "tring msg , "tring.format3@+ello QsU@L val6E tv.set*ext3msg6E I I6E
ad.set0egative7utton3@=an&el@L new
#ialog4nterfa&e.Hn=li&kBistener36 F pu!li& void on=li&k3#ialog4nterfa&e dlgL int whi&h6 F dlg.&an&el36E I I6E
ad.show36E II
'licking on the button widget will display the Alertialog. It has an 9ditText to receive the
input from a user.
)lert#ialog.7uilder ad , new )lert#ialog.7uilder3this6E
ad.set*itle3@[email protected]@Dnter 'our name@6E
8e set a title and a message for the dialog.
final Ddit*ext input , new Ddit*ext3this6Ead.setiew3input6E
8e add the Ddit*ext widget to the dialog.
ad.set(ositive7utton3@Hk@L new #ialog4nterfa&e.Hn=li&kBistener36 Fpu!li& void on=li&k3#ialog4nterfa&e dlgL int whi&h6 F "tring val , input.get*ext36.to"tring36E "tring msg , "tring.format3@+ello QsU@L val6E tv.set*ext3msg6E II6E
'licking on the )= button of the dialog, we get the text from the 9ditText widget. The text
used to format a greeting which is set to the Text!iew.
ad.set0egative7utton3@=an&el@L new #ialog4nterfa&e.Hn=li&kBistener36 F pu!li& void on=li&k3#ialog4nterfa&e dlgL int whi&h6 F dlg.&an&el36E
B$
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 73/77
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 74/77
bitmaps. A ;rawable is an obect that can be drawn. <nlike a !iew, a rawable does not
have any facility to receive events or otherwise interact with the user.
($al shape
8e are going to draw a circle on a !iew. The circle is defined in an E2L file. The manifestfile does not need to be modified.
oval.xml>?xml version,@1.@ en&oding,@utf-8@?<>shape xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidshape,@oval@<
>solidandroid&olor,@VWWWWWW@/<
>sizeandroidwidth,@5dp@
androidheight,@5dp@/<>/shape<
In the oval.xml file we create a circle shape. 8e define its colour and si"e. The oval.xml file
is located in the res0drawable directory. The directory had to be created.
main.xml>?xml version,@1.@ en&oding,@utf-8@?<>BinearBa'out xmlnsandroid,@http//s&hemas.android.&om/apk/res/android@ androidorientation,@verti&al@ androidla'out_width,@fill_parent@ androidla'out_height,@fill_parent@
<
>iew androidla'out_width,@1dp@ androidla'out_height,@1dp@ androidla'out_margin*op,@dp@ android!a&kground,@Adrawa!le/oval@ /<
>/BinearBa'out<
In the main.xml file, we define a simple !iew. The background of this view is filled with our
drawable obect.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<Hval"hape>/string<>/resour&es<
6esources file.
2ainActivity.avapa&kage &om.zet&ode.ovalshapeE
import android.app.)&tivit'Eimport android.os.7undleE
BD
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 75/77
pu!li& &lass Main)&tivit' extends )&tivit'F AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F
super.on=reate3saved4nstan&e"tate6E set=ontentiew3%.la'out.main6E II
The file ust loads the defined layout.
?igure@ )val *hape
Drawing a rectangle
In the second example, we will draw a rectangle on a !iew. It will be drawn in the on#raw36
method of the !iew. *ince we will be drawing on an existing !iew, we will have a
predefined 'anvas with its /itmap. 8e do not need to worry about them. The manifest file isnot modified. In this example the main.xml file will not be needed.
strings.xml>?xml version,@1.@ en&oding,@utf-8@?<>resour&es< >string name,@app_name@<#raw%e&t>/string<>/resour&es<
6esources.
raw!iew.avapa&kage &om.zet&ode.drawre&tE
import android.&ontent.=ontextEimport android.graphi&s.=anvasEimport android.graphi&s.=olorEimport android.graphi&s.(aintEimport android.view.iewE
pu!li& &lass #rawiew extends iewF (aint paint , new (aint36E
pu!li& #rawiew3=ontext &ontext6
F super3&ontext6E
BG
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 76/77
paint.set=olor3=olor.K%DD06E I
AHverride pu!li& void on#raw3=anvas &anvas6
F
&anvas.draw%e&t3L L 1L 1L paint6E II
8e have a custom raw!iew class. The file is located in the src0com0"etcode0drawrect0
directory.
pu!li& &lass #rawiew extends iew
The custom raw!iew class inherits from the base !iew class.
(aint paint , new (aint36E
An instance of the +aint class is created. It will define a colour for drawing.
paint.set=olor3=olor.K%DD06E
8e will paint in green colour.
AHverridepu!li& void on#raw3=anvas &anvas6F &anvas.draw%e&t3L L 1L 1L paint6E
I
The drawing is performed in the on#raw36 method. The method provides the =anvas obect
for us. 8e call the draw%e&t36 to draw the rectangle on the !iew.
2ainActivity.avapa&kage &om.zet&ode.drawre&tE
import android.app.)&tivit'Eimport android.graphi&s.=olorEimport android.os.7undleE
pu!li& &lass Main)&tivit' extends )&tivit'F AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E
#rawiew drawiew , new #rawiew3this6E drawiew.set7a&kground=olor3=olor.N+4*D6E set=ontentiew3drawiew6E II
In the 2ainActivity.ava source file we set the custom raw!iew to be the content !iew ofthe Activity.
BH
8/13/2019 ZetCode Android Tutorial
http://slidepdf.com/reader/full/zetcode-android-tutorial 77/77
#rawiew drawiew , new #rawiew3this6E
8e create an instance of the #rawiew class.
drawiew.set7a&kground=olor3=olor.N+4*D6E
8e specify the background colour for the !iew.
set=ontentiew3drawiew6E
The raw!iew becomes the content !iew of the Activity.
?igure@ 6ectangle
In this chapter of the Android development tutorial, we did dome basic drawing.