Sunteți pe pagina 1din 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 e uipments, 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 e uipment, 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 +ro,ect for maintaining and developing of the Android )*. Android is being developed uickly- new versions of Android are fre uently 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,

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 ob,ect. 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 ob,ect that holds other !iew 3and !iew(roup4 ob,ects 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 uni uely 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 A.T bundle or single *.= tools. 8e will go with the latter.
$ ls -sh android-sdk_r21-linux.tgz 88M 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.

$ pwd /home/ an!odnar/!in/android-sdk-linux $ ls add-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 the android command line tool.

?igure@ Android *.= 2anager


$ ls add-ons do&s platforms platform-tools samples "#$ %eadme.txt sour&es s'stem-images temp tools

These are the contents of the android-sdk-linux directory after installing additional tools.
export ()*+,$()*+-./!in/android-sdk-linux/tools export ()*+,$()*+-./!in/android-sdk-linux/platform-tools

8e add the tools and platform-tools directories to the +ATA 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!.

&

'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 )vaila!le 0ame(ath*arget)74"kin--------0ame(ath*arget)74"kinlist avd )ndroid /irtual #evi&es)/#1 /home/ an!odnar/.android/avd/)/#1.avd )ndroid 2.2 3)(4 level 156 armea!i-v5a 128x288 )/#2 /home/ an!odnar/.android/avd/)/#2.avd )ndroid 2.2 3)(4 level 156 armea!i-v5a 228x128

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

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 pro e&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 pro,ect with the android &reate pro e&t command. The target option specifies the Android application framework version. The name option determines the name of the pro,ect. The path is the location of our pro,ect directory. The activity is the name of our default activity. ?inally, the package is the name of the package namespace for our pro,ect. The command creates a #ava file for the main activity, several directories and E2L files.
$ ls )ndroidManifest.xml ant.properties !in !uild.xml li!s lo&al.properties proguard-pro e&t.txt pro e&t.properties res sr&

These are the files and directories created by the android &reate pro e&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 pro,ect. ?inally, the local.properties and the project.properties are property files of the Android pro,ect. Android2anifest.xml
>?xml version,@1.8@ en&oding,@utf-8@?< >manifest xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ pa&kage,@&om.zet&ode.first@ android-version=ode,@1@

android-version0ame,@1.8@< >appli&ation android-la!el,@Astring/app_name@ android-i&on,@Adrawa!le/i&_laun&her@< >a&tivit' android-name,@Main)&tivit'@ android-la!el,@Astring/app_name@< >intent-filter< >a&tion android-name,@android.intent.a&tion.M)40@ /< >&ategor' android-name,@android.intent.&ategor'.B)C0=+D%@ /< >/intent-filter< >/a&tivit'< >/appli&ation< >/manifest<

This is the pro,ect manifest file. It describes some basic characteristics of the Android pro,ect. 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. It specifies 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.8@ 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.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >*ext/iew android-la'out_width,@fill_parent@ android-la'out_height,@wrap_&ontent@ android-text,@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

pa&kage &om.zet&ode.firstE import android.app.)&tivit'E import 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=ontent/iew3%.la'out.main6E I I

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 pro,ect 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.d arlist.&a&he proguard.txt res

The final Android package is created in the bin directory. The name of our archive file is !irst-debug.ap".

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 I/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.

Android2anifest.xml
>?xml version,@1.8@ en&oding,@utf-8@?< >manifest xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ pa&kage,@&om.zet&ode.finish@ android-version=ode,@1@ android-version0ame,@1.8@< >appli&ation android-la!el,@Astring/app_name@ android-i&on,@Adrawa!le/i&_laun&her@< >a&tivit' android-name,@Main)&tivit'@ android-la!el,@Astring/app_name@< >intent-filter< >a&tion android-name,@android.intent.a&tion.M)40@ /< >&ategor' android-name,@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.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >7utton android-la'out_height,@wrap_&ontent@ android-la'out_width,@wrap_&ontent@ android-la'out_margin*op,@18dip@ android-text,@Astring/!tnla!el@ android-on=li&k,@on=li&k@ /< >/BinearBa'out<

In the main.xml layout file, we define one button widget with the I/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#la out_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 click event. All we need to do is to define the on'lick34 method in the relevant #ava source file. strings.xml
>?xml version,@1.8@ 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.

2ainActivity.,ava
pa&kage &om.zet&ode.finishE import android.app.)&tivit'E import android.view./iewE import 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=ontent/iew3%.la'out.main6E I pu!li& void on=li&k3/iew view6 F finish36E I

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 a short 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.8@ en&oding,@utf-8@?< >manifest xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ pa&kage,@&om.zet&ode.toast@ android-version=ode,@1@ android-version0ame,@1.8@< >appli&ation android-la!el,@Astring/app_name@ android-i&on,@Adrawa!le/i&_laun&her@< >a&tivit' android-name,@Main)&tivit'@ android-la!el,@Astring/app_name@< >intent-filter<

7%

>a&tion android-name,@android.intent.a&tion.M)40@ /< >&ategor' android-name,@android.intent.&ategor'.B)C0=+D%@ /< >/intent-filter< >/a&tivit'< >/appli&ation< >/manifest<

This is the manifest file. main.xml


>?xml version,@1.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >7utton android-id,@AJid/!tn4d@ android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ android-la'out_margin*op,@18dip@ android-text,@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 find/iew7'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. *ubse uent references to the element in the E2L file would be used without the plus sign. 3?or example in layout managers.4 strings.xml
>?xml version,@1.8@ 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.,ava
import import import import import import import import pa&kage &om.zet&ode.toastE android.app.)&tivit'E android.os.7undleE android.view./iewE android.view./iew.Hn=li&kBistenerE android.view.Kravit'E android.widget.7uttonE android.widget.*oastE android.&ontent.=ontextE

pu!li& &lass Main)&tivit' extends )&tivit' F AHverride

77

pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontent/iew3%.la'out.main6E initC436E I pu!li& void initC436 F 7utton !tn , 37utton6 find/iew7'4d3%.id.!tn4d6E !tn.setHn=li&kBistener3new Hn=li&kBistener36 F AHverride pu!li& void on=li&k3/iew arg86 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 8L 86E toast.show36E I6E I I I

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 import import import import android.view./iew.Hn=li&kBistenerE android.view.Kravit'E android.widget.7uttonE android.widget.*oastE 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 to the button widget.
7utton !tn , 37utton6 find/iew7'4d3%.id.!tn4d6E

8e get the reference to the button widget that we have specified in the main.xml file. 8e use the find/iew7'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&kBistener36 F AHverride

7$

pu!li& void on=li&k3/iew arg86 F ... I I6E

8e add the Hn=li&kBistener to the button widged. Listeners can be set up in various ways. Aere we use an anonymous inner class.
=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 8L 86E toast.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 toast in 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.*ext/iew 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&

Android2anifest.xml
>?xml version,@1.8@ en&oding,@utf-8@?< >manifest xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ pa&kage,@&om.zet&ode.&he&k!ox@ android-version=ode,@1@ android-version0ame,@1.8@< >appli&ation android-la!el,@Astring/app_name@ android-i&on,@Adrawa!le/i&_laun&her@< >a&tivit' android-name,@Main)&tivit'@ android-la!el,@Astring/app_name@< >intent-filter< >a&tion android-name,@android.intent.a&tion.M)40@ /< >&ategor' android-name,@android.intent.&ategor'.B)C0=+D%@ /< >/intent-filter< >/a&tivit'< >/appli&ation< >/manifest<

The manifest file. main.xml


>?xml version,@1.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >=he&k7ox android-id,@AJid/&!_id@ android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ android-text,@Astring/&!la!el@ /< >/BinearBa'out<

The I'heck/oxJ element creates a 'heck/ox widget. strings.xml


>?xml version,@1.8@ 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.,ava


pa&kage &om.zet&ode.&he&k!oxE import import import import import android.app.)&tivit'E android.os.7undleE android.view./iewE android.view./iew.Hn=li&kBistenerE android.widget.=he&k7oxE

pu!li& &lass Main)&tivit' extends )&tivit' F private =he&k7ox &!E

7D

AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontent/iew3%.la'out.main6E initC436E I pu!li& void initC436 F &! , 3=he&k7ox6 find/iew7'4d3%.id.&!_id6E &!.set=he&ked3true6E &!.setHn=li&kBistener3new Hn=li&kBistener36 F AHverride pu!li& void on=li&k3/iew v6 F =he&k7ox &! , 3=he&k7ox6 vE if 3&!.is=he&ked366 F set*itle3@=he&k7ox@6E I else F set*itle3@@6E I I6E I I I

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 find/iew7'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&kBistener36 F AHverride pu!li& void on=li&k3/iew v6 F =he&k7ox &! , 3=he&k7ox6 vE if 3&!.is=he&ked366 F

7G

set*itle3@=he&k7ox@6E I else F set*itle3@@6E I I6E I

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.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ android-orientation,@verti&al@ < >7utton android-id,@AJid/!utton1@ android-la'out_width,@wrap_&ontent@

7H

android-la'out_height,@wrap_&ontent@ android-la'out_margin,@Mdp@ android-on=li&k,@on=li&ked@ android-text,@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.8@ en&oding,@utf-8@?< >resour&es< >string name,@app_name@<Crl>/string< >string name,@!tn_title@</isit>/string< >/resour&es<

*tring resources. 2ainActivity.,ava


import import import import import pa&kage &om.zet&ode.urlE android.app.)&tivit'E android.os.7undleE android.&ontent.4ntentE android.net.CriE 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=ontent/iew3%.la'out.main6E I pu!li& void on=li&ked3/iew view6 F 4ntent intent , new 4ntent34ntent.)=*4H0_/4DNL Cri.parse3@http-//www.google.&om@66E start)&tivit'3intent6E I I

This is the 2ainActivity.,ava source file.


pu!li& void on=li&ked3/iew view6 F 4ntent intent , new 4ntent34ntent.)=*4H0_/4DNL Cri.parse3@http-//www.google.&om@66E start)&tivit'3intent6E I

In the on=li&ked36 method, we create an Intent ob,ect and start a new activity. 8ith this implicit intent, we tell Android to start a default web browser with google.com web page opened.

7B

?igure@ 8eb page in Android emulator

Explicit intent
In explicit intents, we provide the exact class to be run. Android2anifest.xml
>?xml version,@1.8@ en&oding,@utf-8@?< >manifest xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ pa&kage,@&om.zet&ode.expli&it@ android-version=ode,@1@ android-version0ame,@1.8@< >appli&ation android-la!el,@Astring/app_name@ android-i&on,@Adrawa!le/i&_laun&her@< >a&tivit' android-name,@Main)&tivit'@ android-la!el,@Astring/app_name@< >intent-filter< >a&tion android-name,@android.intent.a&tion.M)40@ /< >&ategor' android-name,@android.intent.&ategor'.B)C0=+D%@ /< >/intent-filter< >/a&tivit'< >a&tivit' android-name,@.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.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >7utton android-id,@AJid/!utton1@ android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@

7K

android-la'out_margin,@Mdp@ android-on=li&k,@on=li&ked@ android-text,@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.8@ 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.,ava
import import import import pa&kage &om.zet&ode.expli&itE android.app.)&tivit'E android.os.7undleE android.view./iewE 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=ontent/iew3%.la'out.main6E I pu!li& void on=li&ked3/iew view6 F 4ntent intent , new 4ntent3thisL 0ext)&tivit'.&lass6E start)&tivit'3intent6E I I

This is the source for the main activity. In the on'licked34 method, we start a new explicit intent.
pu!li& void on=li&ked3/iew view6 F 4ntent intent , new 4ntent3thisL 0ext)&tivit'.&lass6E start)&tivit'3intent6E I

The second parameter of the Intent constructor is the class name to be invoked. The activity is started with the start)&tivit'36 method. 7L

5extActivity.,ava
pa&kage &om.zet&ode.expli&itE import import import import android.app.)&tivit'E android.os.7undleE android.widget.*ext/iewE 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 *ext/iew tv , new *ext/iew3this6E tv.set*ext3@0ext s&reen@6E la'.add/iew3tv6E I I set=ontent/iew3la'6E

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.8@ en&oding,@utf-8@?< >manifest xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ pa&kage,@&om.zet&ode.swit&h2@ android-version=ode,@1@ android-version0ame,@1.8@< >appli&ation android-la!el,@Astring/app_name@ android-i&on,@Adrawa!le/i&_laun&her@< >a&tivit' android-name,@.:irst"&reen@< >intent-filter<

$%

>a&tion android-name,@android.intent.a&tion.M)40@ /< >&ategor' android-name,@android.intent.&ategor'.B)C0=+D%@ /< >/intent-filter< >/a&tivit'< >a&tivit' android-name,@."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.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >Ddit*ext android-id,@AJid/edit4d@ android-la'out_width,@fill_parent@ android-la'out_height,@wrap_&ontent@ android-la'out_margin*op,@18dip@ android-la'out_margin7ottom,@18dip@ android-hint,@Astring/et+int@ /< >7utton android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ android-text,@Astring/!tn_send@ android-on=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.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >*ext/iew android-id,@AJid/tv4d@ android-la'out_width,@fill_parent@ android-la'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.8@ en&oding,@utf-8@?< >resour&es<

$7

>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.,ava


pa&kage &om.zet&ode.swit&h2E import import import import import android.app.)&tivit'E android.os.7undleE android.&ontent.4ntentE android.view./iewE 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=ontent/iew3%.la'out.s&reen16E I iname , 3Ddit*ext6 find/iew7'4d3%.id.edit4d6E

pu!li& void sendMessage3/iew view6 F 4ntent swit&h*o , new 4ntent3thisL "e&ond"&reen.&lass6E swit&h*o.putDxtra3@name@L iname.get*ext36.to"tring366E start)&tivit'3swit&h*o6E I

The ?irst*creen is the main activity. The sendMessage36 method is called, when we click on the button.
pu!li& void sendMessage3/iew view6 F 4ntent swit&h*o , new 4ntent3thisL "e&ond"&reen.&lass6E swit&h*o.putDxtra3@name@L iname.get*ext36.to"tring366E start)&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

$$

import android.os.7undleE import android.&ontent.4ntentE import android.widget.*ext/iewE 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=ontent/iew3%.la'out.s&reen26E I setupC436E

void setupC436 F set*itle3@"e&ond s&reen@6E *ext/iew tv , 3*ext/iew6 find/iew7'4d3%.id.tv4d6E 4ntent i , get4ntent36E "tring name , i.get"tringDxtra3@name@6E tv.set*ext3@Oou have entered- @ J name6E I I

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@name@6E tv.set*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 our components, we use speciali"ed non visible ob,ects called layout managers.

$&

There are several layout managers in Android. A &inear&a out lines up its views in one row or column. A !rame&a out is a simple layout manager used to display one view. A 3elative&a out 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&a out 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.8@ en&oding,@utf-8@?< >:rameBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-la'out_gravit',@top@ android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ < >4mage/iew android-la'out_height,@mat&h_parent@ android-la'out_width,@mat&h_parent@ android-sr&,@Adrawa!le/zamok@ /< >/:rameBa'out<

In the ?rameLayout manager, we put one Image!iew.


>:rameBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-la'out_gravit',@top@ android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ <

The :rameBa'out is big enough to display the 4mage/iew by setting the layout width and height to wrap_&ontent. It is pushed to the top using the la'out_gravit' attribute.
>4mage/iew android-la'out_height,@mat&h_parent@ android-la'out_width,@mat&h_parent@ android-sr&,@Adrawa!le/zamok@ /<

The 4mage/iew displays an image. The image is located in a subdirectory of the res directory.

$D

?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.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@horizontal@ android-la'out_width,@mat&h_parent@ android-la'out_height,@mat&h_parent@ < >7utton android-la'out_height,@wrap_&ontent@ android-la'out_width,@wrap_&ontent@ android-text,@7utton1@ /< >7utton android-la'out_height,@wrap_&ontent@ android-la'out_width,@wrap_&ontent@ android-text,@7utton2@ /< >7utton android-la'out_height,@wrap_&ontent@ android-la'out_width,@wrap_&ontent@ android-text,@7utton1@ /< >7utton android-la'out_height,@wrap_&ontent@ android-la'out_width,@wrap_&ontent@ android-text,@7utton2@ /< >/BinearBa'out<

8e have a hori"ontal BinearBa'out. In this layout, we add four buttons.


>BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@

$G

android-orientation,@horizontal@ android-la'out_width,@mat&h_parent@ android-la'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 android-la'out_height,@wrap_&ontent@ android-la'out_width,@wrap_&ontent@ android-text,@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 buttons with a LinearLayout manager. 2ainActivity.,ava
import import import import pa&kage &om.zet&ode.!tnrow2E android.app.)&tivit'E android.os.7undleE android.widget.7uttonE 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

7utton !tn1 , new 7utton3this6E !tn1.set*ext3@7utton@6E 7utton !tn2 , new 7utton3this6E !tn2.set*ext3@7utton@6E BinearBa'out ll , new BinearBa'out3this6E ll.setHrientation3BinearBa'out.+H%4PH0*)B6E ll.add/iew3!tn16E ll.add/iew3!tn26E ll.add/iew3!tn16E ll.add/iew3!tn26E set=ontent/iew3ll6E I I

?our buttons are placed in a hori"ontal LinearLayout. 8e will not use the layout E2L file in this 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'out3this6E ll.setHrientation3BinearBa'out.+H%4PH0*)B6E

A hori"ontal BinearBa'out is created.


ll.add/iew3!tn16E ll.add/iew3!tn26E ll.add/iew3!tn16E ll.add/iew3!tn26E

/uttons are added to the layout manager.


set=ontent/iew3ll6E

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.8@ en&oding,@utf-8@?< >:rameBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ android-la'out_gravit',@&enter@ <

$B

>BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@mat&h_parent@ android-la'out_height,@mat&h_parent@ < >7utton android-la'out_height,@wrap_&ontent@ android-la'out_width,@wrap_&ontent@ android-text,@7utton@ /< >7utton android-la'out_height,@wrap_&ontent@ android-la'out_width,@wrap_&ontent@ android-text,@7utton@ /< >7utton android-la'out_height,@wrap_&ontent@ android-la'out_width,@wrap_&ontent@ android-text,@7utton@ /< >7utton android-la'out_height,@wrap_&ontent@ android-la'out_width,@wrap_&ontent@ android-text,@7utton@ /< >/BinearBa'out< >/:rameBa'out<

A LinearLayout manager with four buttons is placed in the ?rameLayout manager.


>:rameBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ android-la'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 xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@mat&h_parent@ android-la'out_height,@mat&h_parent@ <

A vertical LinearLayout is created.

$K

?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.8@ en&oding,@utf-8@?< >%elativeBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >Ddit*ext android-id,@AJid/et4d@ android-la'out_margin*op,@18dp@ android-la'out_width,@mat&h_parent@ android-la'out_height,@wrap_&ontent@ /< >7utton android-id,@AJid/!tn_send4d@ android-la'out_!elow,@AJid/et4d@ android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ android-text,@"end@ /< >7utton android-id,@AJid/!tn_&lear4d@ android-la'out_!elow,@AJid/et4d@ android-la'out_to%ightHf,@AJid/!tn_send4d@ android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ android-text,@=lear@ /< >/%elativeBa'out<

$L

The E2L code displays an 9ditText with two buttons.


>Ddit*ext android-id,@AJid/et4d@ android-la'out_margin*op,@18dp@ android-la'out_width,@mat&h_parent@ android-la'out_height,@wrap_&ontent@ /<

The Ddit*ext will be stretched from right to left by setting the android-la'out_width to android-mat&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 android-la'out_margin*op property.
>7utton android-id,@AJid/!tn_send4d@ android-la'out_!elow,@AJid/et4d@ android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ android-text,@"end@ /<

The *end button widget will be placed below the 9ditText widget. To accomplish this, we use the android-la'out_!elow property. 5ote that we reference the id of the widget that we relate to.
>7utton android-id,@AJid/!tn_&lear4d@ android-la'out_!elow,@AJid/et4d@ android-la'out_to%ightHf,@AJid/!tn_send4d@ android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ android-text,@=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 android-la'out_!elow and the android-la'out_to%ightHf property.

?igure@ 6elativeLayout example

&%

%rid
A 4rid&a out 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.8@ en&oding,@utf-8@?< >KridBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-la'out_width,@mat&h_parent@ android-la'out_height,@mat&h_parent@ < >7utton android-text,@38L 86@ android-la'out_row,@8@ android-la'out_&olumn,@8@ /< >7utton android-la'out_row,@8@ android-la'out_&olumn,@1@ android-la'out_&olumn"pan,@2@ android-la'out_gravit',@fill_horizontal@ /< >7utton android-text,@38L 16@ android-la'out_row,@8@ android-la'out_&olumn,@1@ /< >7utton android-text,@38L 26@ android-la'out_row,@8@ android-la'out_&olumn,@2@ /< >7utton android-la'out_row,@1@ android-la'out_&olumn,@8@ android-la'out_row"pan,@1@ android-la'out_&olumn"pan,@M@ android-la'out_gravit',@fill@ /< >7utton android-text,@=enter@ android-la'out_row,@2@ android-la'out_&olumn,@8@ android-la'out_&olumn"pan,@M@ android-la'out_gravit',@&enter_horizontal@ /< >7utton android-text,@%ight@ android-la'out_row,@M@ android-la'out_&olumn,@8@ android-la'out_&olumn"pan,@M@ android-la'out_gravit',@right@ /< >/KridBa'out<

&7

In the example we put a few buttons in a (ridLayout. 8e show how a button can stretch over several cells.
>7utton android-text,@38L 86@ android-la'out_row,@8@ android-la'out_&olumn,@8@ /<

<sing the la'out_row and la'out_&olumn properties, we place a button at top-left cell. The indeces start from "ero.
>7utton android-la'out_row,@8@ android-la'out_&olumn,@1@ android-la'out_&olumn"pan,@2@ android-la'out_gravit',@fill_horizontal@ /<

This button will span two columns. The la'out_gravit' property will cause the button to fill the two columns.
>7utton android-la'out_row,@1@ android-la'out_&olumn,@8@ android-la'out_row"pan,@1@ android-la'out_&olumn"pan,@M@ android-la'out_gravit',@fill@ /<

This button will span three rows and five columns.


>7utton android-text,@=enter@ android-la'out_row,@2@ android-la'out_&olumn,@8@ android-la'out_&olumn"pan,@M@ android-la'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.

&$

?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 it shows 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.8@ en&oding,@utf-8@?< >manifest xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ pa&kage,@&om.zet&ode.finish@ android-version=ode,@1@ android-version0ame,@1.8@< >appli&ation android-la!el,@Astring/app_name@ android-i&on,@Adrawa!le/i&_laun&her@< >a&tivit' android-name,@Main)&tivit'@ android-la!el,@Astring/app_name@< >intent-filter< >a&tion android-name,@android.intent.a&tion.M)40@ /<

&&

>&ategor' android-name,@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.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >"pinner android-id,@AJid/spn@ android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ android-entries,@Aarra'/dlangs@ android-la'out_margin*op,@18dip@ android-prompt,@Astring/spn_title@ /< >*ext/iew android-id,@AJid/tv4d@ android-la'out_width,@fill_parent@ android-la'out_height,@wrap_&ontent@ android-la'out_margin*op,@18dip@ /< >/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.8@ 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.,ava
pa&kage &om.zet&ode.spinnerE

&D

import import import import import import import

android.app.)&tivit'E android.os.7undleE android.view./iewE android.widget.*ext/iewE android.widget."pinnerE android.widget.)dapter/iewE android.widget.)dapter/iew.Hn4tem"ele&tedBistenerE

pu!li& &lass Main)&tivit' extends )&tivit' implements Hn4tem"ele&tedBistener F private *ext/iew tvE AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontent/iew3%.la'out.main6E tv , 3*ext/iew6 find/iew7'4d3%.id.tv4d6E "pinner spn , 3"pinner6 find/iew7'4d3%.id.spn6E spn.setHn4tem"ele&tedBistener3this6E I AHverride pu!li& void on4tem"ele&ted3)dapter/iew>?< parentL /iew vL int posL long id6 F "tring item , parent.get4tem)t(osition3pos6.to"tring36E tv.set*ext3item6E I AHverride pu!li& void on0othing"ele&ted3)dapter/iew>?< arg86 F tv.set*ext3@@6E I

The selected item from the *pinner widget is displayed in the Text!iew widget.
pu!li& &lass Main)&tivit' extends )&tivit' implements Hn4tem"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 find/iew7'4d3%.id.spn6E spn.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)dapter/iew>?< parentL /iew vL int posL long id6 F

&G

"tring item , parent.get4tem)t(osition3pos6.to"tring36E tv.set*ext3item6E I

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 con,unction 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.8@ en&oding,@utf-8@?< >manifest xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ pa&kage,@&om.zet&ode.toast@ android-version=ode,@1@ android-version0ame,@1.8@< >appli&ation android-la!el,@Astring/app_name@ android-i&on,@Adrawa!le/i&_laun&her@< >a&tivit' android-name,@Main)&tivit'@ android-la!el,@Astring/app_name@< >intent-filter< >a&tion android-name,@android.intent.a&tion.M)40@ /< >&ategor' android-name,@android.intent.&ategor'.B)C0=+D%@ /< >/intent-filter< >/a&tivit'< >/appli&ation< >/manifest<

This is the manifest file. main.xml


>?xml version,@1.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@

&H

android-la'out_height,@fill_parent@ < >"pinner android-id,@AJid/spn4d@ android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ android-la'out_margin*op,@18dip@ android-prompt,@Astring/spn_title@ /< >*ext/iew android-id,@AJid/tv4d@ android-la'out_width,@fill_parent@ android-la'out_height,@wrap_&ontent@ android-la'out_margin*op,@18dip@ /< >/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.8@ 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.,ava


pa&kage &om.zet&ode.spinner2E import import import import import import import import import import ava.util.)rra'BistE ava.util.BistE android.app.)&tivit'E android.os.7undleE android.view./iewE android.widget."pinnerE android.widget.)rra')dapterE android.widget.*ext/iewE android.widget.)dapter/iewE android.widget.)dapter/iew.Hn4tem"ele&tedBistenerE

pu!li& &lass Main)&tivit' extends )&tivit' implements Hn4tem"ele&tedBistener F private *ext/iew tvE private "pinner spnE AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontent/iew3%.la'out.main6E setup36E

&B

I pu!li& void setup36 F tv , 3*ext/iew6 find/iew7'4d3%.id.tv4d6E spn , 3"pinner6 find/iew7'4d3%.id.spn4d6E fill"pinner3spn6E spn.setHn4tem"ele&tedBistener3this6E

pu!li& void fill"pinner3"pinner spn6 F 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#own/iew%esour&e3android.%.la'out.simple_spinner_item6E I spn.set)dapter3da6E

id6

AHverride pu!li& void on4tem"ele&ted3)dapter/iew>?< parentL /iew vL int posL long F I "tring item , parent.get4tem)t(osition3pos6.to"tring36E tv.set*ext3item6E

AHverride pu!li& void on0othing"ele&ted3)dapter/iew>?< arg86 F tv.set*ext3@@6E I I

In the 2ainActivity.,ava source file we fill the *pinner widget with data and implement the )nItem*electedListener for the widget.
spn , 3"pinner6 find/iew7'4d3%.id.spn4d6E fill"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<36E lst.add3@('thon@6E lst.add3@(+(@6E lst.add3@(erl@6E lst.add3@*&l@6E lst.add3@%u!'@6E

An )rra'Bist is created and filled with strings. &K

)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#own/iew%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.

&L

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.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >"eek7ar android-id,@AJid/s!4d@ android-la'out_width,@fill_parent@ android-la'out_height,@wrap_&ontent@ android-la'out_margin,@18dp@ android-max,@188@ android-progress,@M8@ /< >*ext/iew android-id,@AJid/tv4d@ android-la'out_width,@fill_parent@ android-la'out_height,@wrap_&ontent@ android-la'out_marginBeft,@18dp@ /< >/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.8@ en&oding,@utf-8@?< >resour&es< >string name,@app_name@<"eek7ar>/string< >string name,@init_tv_value@<M8>/string< >/resour&es<

This is strings.xml resource file. The init>tv>value is the initial value of the Text!iew widget. 2ainActivity.,ava
pa&kage &om.zet&ode.seek!arE import import import import import android.app.)&tivit'E android.os.7undleE android.widget.*ext/iewE android.widget."eek7arE android.widget."eek7ar.Hn"eek7ar=hangeBistenerE

pu!li& &lass Main)&tivit' extends )&tivit' implements Hn"eek7ar=hangeBistener F *ext/iew tvE AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F

D%

super.on=reate3saved4nstan&e"tate6E set=ontent/iew3%.la'out.main6E "eek7ar s! , 3"eek7ar6 find/iew7'4d3%.id.s!4d6E s!.setHn"eek7ar=hangeBistener3this6E tv , 3*ext/iew6 find/iew7'4d3%.id.tv4d6E "tring val , this.get"tring3%.string.init_tv_value6E tv.set*ext3val6E

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 seek7ar6 F // not implemented I AHverride pu!li& void on"top*ra&king*ou&h3"eek7ar seek7ar6 F // not implemented I

The current value from the *eek/ar is set to the Text!iew widget.
pu!li& &lass Main)&tivit' extends )&tivit' implements Hn"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 find/iew7'4d3%.id.s!4d6E s!.setHn"eek7ar=hangeBistener3this6E

8e get the reference to the *eek/ar widget and set a listener for it.
tv , 3*ext/iew6 find/iew7'4d3%.id.tv4d6E "tring val , this.get"tring3%.string.init_tv_value6E tv.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.
AHverride pu!li& void on(rogress=hanged3"eek7ar seek7arL int progressL !oolean fromCser6 F

D7

tv.set*ext3"tring.valueHf3progress66E

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/ar widget.

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.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >(rogress7ar android-id,@AJid/p!4d@ android-la'out_width,@fill_parent@ android-la'out_height,@wrap_&ontent@ st'le,@?android-attr/progress7ar"t'le+orizontal@ android-la'out_margin,@18dp@ /< >*ext/iew android-id,@AJid/tv4d@ android-la'out_width,@fill_parent@ android-la'out_height,@wrap_&ontent@ android-la'out_margin,@18dp@ /< >/BinearBa'out<

D$

In the main.xml layout file, we have a +rogress/ar and a Text!iew. The st'le,@? android-attr/progress7ar"t'le+orizontal@ style makes the +rogress/ar hori"ontal. The default mode of the +rogress/ar is the circular mode. strings.xml
>?xml version,@1.8@ en&oding,@utf-8@?< >resour&es< >string name,@app_name@<(rog7ar>/string< >/resour&es<

*tring resource file. 2ainActivity.,ava


pa&kage &om.zet&ode.prog!ar2E import import import import import import import android.app.)&tivit'E android.os.7undleE android.os.+andlerE android.os.MessageE android.widget.(rogress7arE android.widget.*ext/iewE android.util.BogE

pu!li& &lass Main)&tivit' extends )&tivit' F (rogress7ar p!E *ext/iew tvE int prg , 8E AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontent/iew3%.la'out.main6E p! , 3(rogress7ar6 find/iew7'4d3%.id.p!4d6E tv , 3*ext/iew6 find/iew7'4d3%.id.tv4d6E I new *hread3m'*hread6.start36E

private %unna!le m'*hread , new %unna!le36 F AHverride pu!li& void run36 F while 3prg > 1886 F tr' F hnd.sendMessage3hnd.o!tainMessage366E *hread.sleep31886E I &at&h34nterruptedDx&eption e6 F Bog.e3@D%%H%@L @*hread was 4nterrupted@6E I I

D&

runHnCi*hread3new %unna!le36 F pu!li& void run36 F tv.set*ext3@:inished@6E I I6E I +andler hnd , new +andler36 F AHverride pu!li& void handleMessage3Message msg6 F prgJJE p!.set(rogress3prg6E "tring per& , "tring.valueHf3prg6.to"tring36E tv.set*ext3per&J@Q &ompleted@6E IE I IE I

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.
AHverride pu!li& void run36 F while 3prg > 1886 F tr' F hnd.sendMessage3hnd.o!tainMessage366E *hread.sleep31886E I &at&h34nterruptedDx&eption e6 F Bog.e3@D%%H%@L @*hread was 4nterrupted@6E I I runHnCi*hread3new %unna!le36 F pu!li& void run36 F tv.set*ext3@:inished@6E I I6E I

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

created in the main thread. These components cannot be manipulated in other threads. To work around this, we use either the 9andler ob,ect or call the runHnCi*hread36 method.
runHnCi*hread3new %unna!le36 F pu!li& void run36 F tv.set*ext3@:inished@6E I I6E

)nly the original thread that created a view hierarchy can touch its views. Aere 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 +andler36 F AHverride pu!li& void handleMessage3Message msg6 F prgJJE p!.set(rogress3prg6E "tring per& , "tring.valueHf3prg6.to"tring36E tv.set*ext3per&J@Q &ompleted@6E

I IE

Another way to touch widgets from another thread is to use the 9andler ob,ect. It is used to en ueue 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.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >(rogress7ar android-id,@AJid/p!4d@

DG

android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ /< >*ext/iew android-id,@AJid/tv4d@ android-la'out_width,@fill_parent@ android-la'out_height,@wrap_&ontent@ android-text,@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 st le+,: android#attr/progress6ar5t le, attribute. strings.xml
>?xml version,@1.8@ 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.,ava


import import import import import import import import pa&kage &om.zet&ode.prog!arE android.app.)&tivit'E android.os.7undleE android.os.+andlerE android.os.MessageE android.widget.(rogress7arE android.widget.*ext/iewE android.view./iewE android.util.BogE

pu!li& &lass Main)&tivit' extends )&tivit' F (rogress7ar p!E *ext/iew tvE int prg , 8E AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontent/iew3%.la'out.main6E p! , 3(rogress7ar6 find/iew7'4d3%.id.p!4d6E tv , 3*ext/iew6 find/iew7'4d3%.id.tv4d6E new *hread3m'*hread6.start36E I private %unna!le m'*hread , new %unna!le36 F AHverride pu!li& void run36 F

DH

while 3prg > 1886 F tr' F hnd.sendMessage3hnd.o!tainMessage366E *hread.sleep31886E I &at&h34nterruptedDx&eption e6 F Bog.e3@D%%H%@L @*hread was 4nterrupted@6E I I runHnCi*hread3new %unna!le36 F pu!li& void run36 F tv.set*ext3@:inished@6E p!.set/isi!ilit'3/iew.KH0D6E I I6E

+andler hnd , new +andler36 F AHverride pu!li& void handleMessage3Message msg6 F prgJJE p!.set(rogress3prg6E I IE I IE

The code is similar to the first example with a few modifications.


runHnCi*hread3new %unna!le36 F pu!li& void run36 F tv.set*ext3@:inished@6E p!.set/isi!ilit'3/iew.KH0D6E I I6E

After the task was completed, we hide the +rogress/ar using the set/isi!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

List iew 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 ob,ect is used to 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.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@< >Bist/iew android-id,@AJid/lv4d@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ /< >/BinearBa'out<

In the main.xml file we define one List!iew widget. row.xml


>?xml version,@1.8@ en&oding,@utf-8@?< >*ext/iew xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ android-padding,@18dp@ android-text"ize,@28sp@< >/*ext/iew<

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.8@ en&oding,@utf-8@?< >resour&es< >string name,@app_name@<Bist/iew>/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

>/resour&es<

The names of the planets are specified in the strings.xml file within a string array attribute. 2ainActivity.,ava
import import import import pa&kage &om.zet&ode.listviewE android.app.)&tivit'E android.os.7undleE android.widget.)rra')dapterE android.widget.Bist/iewE

pu!li& &lass Main)&tivit' extends )&tivit' F private Bist/iew lvE private )rra')dapter>"tring< laE AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontent/iew3%.la'out.main6E setupC436E I pu!li& void setupC436 F lv , 3Bist/iew6 find/iew7'4d3%.id.lv4d6E "tringST planets , get%esour&es36.get"tring)rra'3%.arra'.planets6E lv.set)dapter3new )rra')dapter>"tring<3thisL %.la'out.rowL planets66E I I

This is the 2ainActivity.,ava source file.


lv , 3Bist/iew6 find/iew7'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.

DL

?igure@ List!iew widget

!istView widget II
A &istActivit is a special activity that holds a List!iew ob,ect. 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.8@ en&oding,@utf-8@?< >*ext/iew xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ android-padding,@18dp@ android-text"ize,@28sp@< >/*ext/iew<

In the row.xml file we define one Text!iew in each row of a List!iew. strings.xml
>?xml version,@1.8@ en&oding,@utf-8@?< >resour&es< >string name,@app_name@<Bist/iew2>/string< >/resour&es<

This is the strings.xml resource file. 2ainActivity.,ava


pa&kage &om.zet&ode.listview2E import import import import import import import import import android.app.Bist)&tivit'E android.os.7undleE android.view./iewE android.widget.)rra')dapterE android.widget.)dapter/iewE android.widget.)dapter/iew.Hn4tem=li&kBistenerE android.widget.)dapter/iew.Hn4tem"ele&tedBistenerE android.widget.Bist/iewE android.widget.*ext/iewE

G%

pu!li& &lass Main)&tivit' extends Bist)&tivit' implements Hn4tem=li&kBistenerL Hn4tem"ele&tedBistener F AHverride 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 Bist/iew lv , getBist/iew36E lv.setHn4tem=li&kBistener3this6E lv.setHn4tem"ele&tedBistener3this6E I pu!li& void on4tem=li&k3)dapter/iew>?< parentL /iew viewL int positionL long id6 F "tring planet , 33*ext/iew6 view6.get*ext36.to"tring36E set*itle3planet6E I pu!li& void on4tem"ele&ted3)dapter/iew>?< parentL /iew viewL int positionL long id6 F "tring planet , 33*ext/iew6 view6.get*ext36.to"tring36E set*itle3planet6E I pu!li& void on0othing"ele&ted3)dapter/iew>?< parent6 F // not implemented I I

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

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"tate6 F super.on=reate3saved4nstan&e"tate6E setupC436E I

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.row6E la.add3@Mer&ur'@6E la.add3@/enus@6E la.add3@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 ob,ect.


Bist/iew lv , getBist/iew36E lv.setHn4tem=li&kBistener3this6E lv.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)dapter/iew>?< parentL /iew viewL int positionL long id6 F "tring planet , 33*ext/iew6 view6.get*ext36.to"tring36E set*itle3planet6E I

Implementing the Hn4tem=li&kBistener, we have to define the on4tem=li&k36 method. 8e get the planet name from the *ext/iew of the clicked row and set it to the titlebar.
pu!li& void on4tem"ele&ted3)dapter/iew>?< parentL /iew viewL int positionL long id6 F "tring planet , 33*ext/iew6 view6.get*ext36.to"tring36E set*itle3planet6E I pu!li& void on0othing"ele&ted3)dapter/iew>?< parent6 F // not implemented I

G$

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.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >0um!er(i&ker android-id,@AJid/np4d@ android-la'out_margin*op,@Mdp@ android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ /< >*ext/iew android-id,@AJid/tv4d@ android-la'out_width,@wrap_&ontent@

G&

android-la'out_height,@wrap_&ontent@ android-la'out_margin*op,@Mdp@ android-la'out_marginBeft,@Mdp@ android-text,@8@ android-text"ize,@18sp@ /< >/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.8@ en&oding,@utf-8@?< >resour&es< >string name,@app_name@<0um!er(i&ker>/string< >/resour&es<

The strings resource file. 2ainActivity.,ava


import import import import import pa&kage &om.zet&ode.numpi&kE android.app.)&tivit'E android.os.7undleE android.widget.0um!er(i&kerE android.widget.*ext/iewE android.widget.0um!er(i&ker.Hn/alue=hangeBistenerE

pu!li& &lass Main)&tivit' extends )&tivit' F private *ext/iew tvE AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontent/iew3%.la'out.main6E setupC436E I pu!li& void setupC436 F tv , 3*ext/iew6 find/iew7'4d3%.id.tv4d6E 0um!er(i&ker np , 30um!er(i&ker6 find/iew7'4d3%.id.np4d6E np.setHn/alue=hangedBistener3new Hn/alue=hangeBistener36 F pu!li& void on/alue=hange30um!er(i&ker pi&kerL int old/alL int new/al6 F tv.set*ext3"tring.valueHf3new/al66E I I6E np.setMax/alue31886E np.setMin/alue386E

GD

'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 find/iew7'4d3%.id.np4d6E

A reference to the 0um!er(i&ker widget is retrieved from the main.xml file.


np.setHn/alue=hangedBistener3new Hn/alue=hangeBistener36 F pu!li& void on/alue=hange30um!er(i&ker pi&kerL int old/alL int new/al6 F tv.set*ext3"tring.valueHf3new/al66E I I6E

A Hn/alue=hangeBistener is added to the 5umber+icker widget. It will call the on/alue=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.setMax/alue31886E np.setMin/alue386E

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

main.xml
>?xml version,@1.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >*ime(i&ker android-id,@AJid/tp4d@ android-la'out_margin*op,@Mdp@ android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ /< >*ext/iew android-id,@AJid/tv4d@ android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ android-la'out_margin*op,@Mdp@ android-la'out_marginBeft,@Mdp@ android-text"ize,@18sp@ /< >/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.8@ en&oding,@utf-8@?< >resour&es< >string name,@app_name@<*ime(i&ker>/string< >/resour&es<

This is the strings.xml resource file. 2ainActivity.,ava


import import import import import pa&kage &om.zet&ode.timepi&kerE android.app.)&tivit'E android.os.7undleE android.widget.*ime(i&kerE android.widget.*ext/iewE android.widget.*ime(i&ker.Hn*ime=hangedBistenerE

pu!li& &lass Main)&tivit' extends )&tivit' F private *ext/iew tvE AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontent/iew3%.la'out.main6E setupC436E I pu!li& void setupC436 F tv , 3*ext/iew6 find/iew7'4d3%.id.tv4d6E

GH

*ime(i&ker tp , 3*ime(i&ker6 find/iew7'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'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 I I6E

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 I I

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=hangedBistener36 F 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 I I6E

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 tp6 F int h , tp.get=urrent+our36E int m , tp.get=urrentMinute36E

GB

"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 ob,ect to create menus from the E2L file.

GK

(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.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >*ext/iew android-la'out_width,@fill_parent@ android-la'out_height,@wrap_&ontent@ android-text,@Astring/message@ /< >/BinearBa'out<

In the main.xml layout file, we have one Text!iew widget. It will display a welcome message. strings.xml
>?xml version,@1.8@ 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.8@ en&oding,@utf-8@?< >menu xmlns-android,@http-//s&hemas.android.&om/apk/res/android@< >item android-id,@AJid/settings@ android-title,@Astring/om1@ /< >item android-id,@AJid/tools@ android-title,@Astring/om2@ /< >/menu<

This is options_menu.xml file. It defines two menu items. The file is located in the res0menu0 subdirectory.

GL

2ainActivity.,ava
pa&kage &om.zet&ode.opmenuE import import import import import import android.app.)&tivit'E android.os.7undleE android.view.MenuE android.view.Menu4nflaterE android.view.Menu4temE android.widget.*oastE

pu!li& &lass Main)&tivit' extends )&tivit' F AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontent/iew3%.la'out.main6E I AHverride pu!li& !oolean on=reateHptionsMenu3Menu menu6 F Menu4nflater inflater , getMenu4nflater36E inflater.inflate3%.menu.options_menuL menu6E return trueE I AHverride pu!li& !oolean onHptions4tem"ele&ted3Menu4tem item6 F swit&h 3item.get4tem4d366 F &ase %.id.settings*oast.make*ext3Main)&tivit'.thisL @"ettings menu sele&ted.@L *oast.BD0K*+_"+H%*6.show36E return trueE &ase %.id.tools*oast.make*ext3Main)&tivit'.thisL @*ools menu sele&ted.@L *oast.BD0K*+_"+H%*6.show36E return trueE defaultreturn super.onHptions4tem"ele&ted3item6E I I I

To enable an options menu in an activity, we need to override the on=reateHptionsMenu36 and the onHptions4tem"ele&ted36 methods.
AHverride pu!li& !oolean on=reateHptionsMenu3Menu menu6 F Menu4nflater inflater , getMenu4nflater36E inflater.inflate3%.menu.options_menuL menu6E return trueE I

H%

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.
AHverride pu!li& !oolean onHptions4tem"ele&ted3Menu4tem item6 F ... 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.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ <

H7

>Bist/iew android-id,@AJid/lv4d@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ /< >/BinearBa'out<

This is main.xml file. It contais a List!iew widget. strings.xml


>?xml version,@1.8@ 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.8@ en&oding,@utf-8@?< >*ext/iew xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ android-padding,@18dp@ android-text"ize,@28sp@< >/*ext/iew<

This is the row.xml resource file. 9ach row of a List!iew consists of a single Text!iew. 2ainActivity.,ava
import import import import import import import import import import import import import pa&kage &om.zet&ode.&onmenuE android.app.)&tivit'E android.os.7undleE android.widget.)rra')dapterE android.widget.Bist/iewE android.view./iewE android.view.MenuE android.view.Menu4nflaterE android.view.Menu4temE android.view.=ontextMenuE android.view.=ontextMenu.=ontextMenu4nfoE android.widget.)dapter/iew.)dapter=ontextMenu4nfoE ava.util.)rra'sE ava.util.)rra'BistE

H$

pu!li& &lass Main)&tivit' extends )&tivit' F private Bist/iew lvE private )rra')dapter>"tring< laE AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontent/iew3%.la'out.main6E I setupC436E

pu!li& void setupC436 F lv , 3Bist/iew6 find/iew7'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

AHverride pu!li& void on=reate=ontextMenu3=ontextMenu menuL /iew vL =ontextMenu4nfo menu4nfo6 F 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=ontextMenu4nfo6 item.getMenu4nfo36E int pos , info.positionE "tring i , la.get4tem3pos6E swit&h 3item.get4tem4d366 F &ase %.id.del4dla.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&

return trueE defaultreturn 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<36E lst.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.


AHverride pu!li& void on=reate=ontextMenu3=ontextMenu menuL /iew vL =ontextMenu4nfo menu4nfo6 F super.on=reate=ontextMenu3menuL vL menu4nfo6E Menu4nflater inflater , getMenu4nflater36E inflater.inflate3%.menu.&ontext_menuL menu6E I

In the on=reate=ontextMenu36 method we build the context menu from the context>menu.xml file.
AHverride pu!li& !oolean on=ontext4tem"ele&ted3Menu4tem item6 F ... 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.del4dla.remove3i6E return trueE

HD

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.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >7utton android-id,@AJid/!tn4d@ android-la'out_height,@wrap_&ontent@ android-la'out_width,@wrap_&ontent@ android-la'out_margin*op,@18dip@ android-text,@Astring/!tn_la!el@ android-on=li&k,@on=li&k@ /< >*ext/iew

HG

android-id,@AJid/tv4d@ android-la'out_width,@fill_parent@ android-la'out_height,@wrap_&ontent@ android-la'out_margin*op,@18dip@ /< >/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.8@ 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.8@ en&oding,@utf-8@?< >menu xmlns-android,@http-//s&hemas.android.&om/apk/res/android@< >item android-id,@AJid/settings@ android-title,@Astring/pm1@ /< >item android-id,@AJid/tools@ android-title,@Astring/pm2@ /< >/menu<

This is popup_menu.xml file. It defines two menu items. The file is located in the res0menu0 subdirectory. 2ainActivity.,ava
pa&kage &om.zet&ode.popmenuE import import import import import import import android.app.)&tivit'E android.os.7undleE android.view./iewE android.view.Menu4temE android.widget.*ext/iewE android.widget.(opupMenuE android.widget.(opupMenu.HnMenu4tem=li&kBistenerE

pu!li& &lass Main)&tivit' extends )&tivit' implements HnMenu4tem=li&kBistener F private *ext/iew tvE AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontent/iew3%.la'out.main6E tv , 3*ext/iew6 find/iew7'4d3%.id.tv4d6E I

HH

pu!li& void on=li&k3/iew v6 F show(opupMenu3v6E I pu!li& void show(opupMenu3/iew v6 F (opupMenu pm , new (opupMenu3Main)&tivit'.thisL v6E pm.getMenu4nflater36.inflate3%.menu.popup_menuL pm.getMenu366E pm.setHnMenu4tem=li&kBistener3this6E pm.show36E I AHverride pu!li& !oolean onMenu4tem=li&k3Menu4tem item6 F tv.set*ext3item.to"tring36 J @ sele&ted@6E return trueE I

A +opup2enu is displayed after clicking on the button widget.


pu!li& void on=li&k3/iew v6 F show(opupMenu3v6E I

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(opupMenu3/iew v6 F (opupMenu pm , new (opupMenu3Main)&tivit'.thisL v6E pm.getMenu4nflater36.inflate3%.menu.popup_menuL pm.getMenu366E pm.setHnMenu4tem=li&kBistener3this6E pm.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 item6 F tv.set*ext3item.to"tring36 J @ sele&ted@6E return trueE I

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

In this chapter of the Android development tutorial we will talk about dialogs. 8e will discuss the Android Alert.ialog. 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 Alert.ialog to display a message. In the example, we do not need to modify the manifest file. main.xml
>?xml version,@1.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >7utton android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ android-la'out_margin*op,@18dip@ android-on=li&k,@on=li&ked@ android-text,@Astring/!tn_la!el@ /< >/BinearBa'out<

In the main.xml layout file, we have a /utton widget. This button will display an Alert.ialog. strings.xml
>?xml version,@1.8@ 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.,ava


pa&kage &om.zet&ode.displa'sizeE import import import import import import import import android.app.)&tivit'E android.os.7undleE android.view./iewE android.graphi&s.(ointE android.app.)lert#ialogE android.&ontent.#ialog4nterfa&eE android.view.NindowManagerE android.view.#ispla'E

HK

pu!li& &lass Main)&tivit' extends )&tivit' F AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontent/iew3%.la'out.main6E I pu!li& void on=li&ked3/iew 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@Nidth-QdL +eight-Qd@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 I ad.show36E

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 I I return pE

8e use the Alert.ialog to display the si"e of the display.


(oint p , get#ispla'"ize36E

In the custom get.isplay*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@Nidth-QdL +eight-Qd@L p.xL p.'6E ad.setMessage3msg6E ad.set4&on3android.%.drawa!le.i&_dialog_info6E

8e set a title, message and an icon for the dialog.

HL

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

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 (oint36E ds.get"ize3p6E

8e find out the si"e of the display with the get"ize36 method.

?igure@ Alert.ialog showing the si"e of the display

Recei$ing data
The second example uses the Alert.ialog 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%

main.xml
>?xml version,@1.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >7utton android-id,@AJid/!tn4d@ android-la'out_width,@wrap_&ontent@ android-la'out_height,@wrap_&ontent@ android-la'out_margin*op,@18dip@ android-on=li&k,@on=li&ked@ android-text,@Astring/!tn_la!el@ /< >*ext/iew android-id,@AJid/tv4d@ android-la'out_width,@fill_parent@ android-la'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.8@ 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.,ava


pa&kage &om.zet&ode.inputE import import import import import import import android.app.)&tivit'E android.os.7undleE android.app.)lert#ialogE android.view./iewE android.widget.Ddit*extE android.widget.*ext/iewE android.&ontent.#ialog4nterfa&eE

pu!li& &lass Main)&tivit' extends )&tivit' F private *ext/iew tvE AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontent/iew3%.la'out.main6E I tv , 3*ext/iew6 find/iew7'4d3%.id.tv4d6E

B7

pu!li& void on=li&ked3/iew 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.set/iew3input6E 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 I I

'licking on the button widget will display the Alert.ialog. It has an 9ditText to receive the input from a user.
)lert#ialog.7uilder ad , new )lert#ialog.7uilder3this6E ad.set*itle3@4nput@6E ad.setMessage3@Dnter 'our name@6E

8e set a title and a message for the dialog.


final Ddit*ext input , new Ddit*ext3this6E ad.set/iew3input6E

8e add the Ddit*ext widget to the dialog.


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

'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$

I6E

'licking on the 'ancel button will dismiss the dialog.

?igure@ 6eceiving input In this chapter of the Android development tutorial, we have shown two cases of the Alert.ialog.

"rawing
In this chapter of the Android development tutorial we will do some drawing. The Android framework A+I provides $. drawing A+I that allows to render custom graphics. 8e can either draw directly on a 'anvas ob,ect or to modify existing !iews to customi"e their look and feel. .rawing is performed in the on#raw36 method. *imple graphics can be created in the layout E2L file too. 8e use the $anvas ob,ect to perform drawing. 'anvas is an ob,ect that has drawing methods to do the drawing. Actual drawing happens in a 6itmap that is placed into a window. The 7aint class holds the style and colour information about how to draw geometries, text and

B&

bitmaps. A ;rawable is an ob,ect 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 manifest file does not need to be modified. oval.xml
>?xml version,@1.8@ en&oding,@utf-8@?< >shape xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-shape,@oval@< >solid android-&olor,@VWWWWWW@/< >size android-width,@58dp@ android-height,@58dp@/< >/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.8@ en&oding,@utf-8@?< >BinearBa'out xmlns-android,@http-//s&hemas.android.&om/apk/res/android@ android-orientation,@verti&al@ android-la'out_width,@fill_parent@ android-la'out_height,@fill_parent@ < >/iew android-la'out_width,@188dp@ android-la'out_height,@188dp@ android-la'out_margin*op,@Mdp@ 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 ob,ect. strings.xml
>?xml version,@1.8@ en&oding,@utf-8@?< >resour&es< >string name,@app_name@<Hval"hape>/string< >/resour&es<

6esources file. 2ainActivity.,ava


pa&kage &om.zet&ode.ovalshapeE import android.app.)&tivit'E import android.os.7undleE

BD

pu!li& &lass Main)&tivit' extends )&tivit' F AHverride pu!li& void on=reate37undle saved4nstan&e"tate6 F super.on=reate3saved4nstan&e"tate6E set=ontent/iew3%.la'out.main6E I I

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 is not modified. In this example the main.xml file will not be needed. strings.xml
>?xml version,@1.8@ en&oding,@utf-8@?< >resour&es< >string name,@app_name@<#raw%e&t>/string< >/resour&es<

6esources. .raw!iew.,ava
pa&kage &om.zet&ode.drawre&tE import import import import import android.&ontent.=ontextE android.graphi&s.=anvasE android.graphi&s.=olorE android.graphi&s.(aintE android.view./iewE

pu!li& &lass #raw/iew extends /iew F (aint paint , new (aint36E pu!li& #raw/iew3=ontext &ontext6 F super3&ontext6E

BG

paint.set=olor3=olor.K%DD06E

AHverride pu!li& void on#raw3=anvas &anvas6 F &anvas.draw%e&t318L 18L 188L 188L paint6E I I

8e have a custom .raw!iew class. The file is located in the src0com0"etcode0drawrect0 directory.
pu!li& &lass #raw/iew 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.


AHverride pu!li& void on#raw3=anvas &anvas6 F &anvas.draw%e&t318L 18L 188L 188L paint6E I

The drawing is performed in the on#raw36 method. The method provides the =anvas ob,ect for us. 8e call the draw%e&t36 to draw the rectangle on the !iew. 2ainActivity.,ava
pa&kage &om.zet&ode.drawre&tE import android.app.)&tivit'E import android.graphi&s.=olorE import 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 #raw/iew draw/iew , new #raw/iew3this6E draw/iew.set7a&kground=olor3=olor.N+4*D6E set=ontent/iew3draw/iew6E

I I

In the 2ainActivity.,ava source file we set the custom .raw!iew to be the content !iew of the Activity.

BH

#raw/iew draw/iew , new #raw/iew3this6E

8e create an instance of the #raw/iew class.


draw/iew.set7a&kground=olor3=olor.N+4*D6E

8e specify the background colour for the !iew.


set=ontent/iew3draw/iew6E

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.

BB

S-ar putea să vă placă și