Sie sind auf Seite 1von 115

Android Programming Painless by Camilus Raynaldo

Copyright 2012 Camilus Raynaldo. All rights reserved.

Portions of the book are exact reproductions or modifications of work created and shared by Google and are used according to terms described in the Apache 2.0 license. Some Ja a examples used in chapter ! are from http"##www.tutorialspoint.com and creati e common work

$his book is totally free and is open to anyone wishing to make their first steps in Android programming. %ou can use this book for educational purposes& it is prohibited to make any commercial use.

Note: $he Android de eloper website http"##de eloper.android.com#index.html is


essential for de eloping android applications.

'ebsite" http"##keroob.com#index.php#andro

(o er )mage by Acuna (esar *acunacesar+gmail.com,

!00

(hapter !" -b.ect -riented Programming (oncept...................................................../


Creating objects.......................................................................................................................................6 Java Programming...................................................................................................................................8

(hapter 2" Jelly 0ean 1eatures............................................................................22


Installing Android...................................................................................................................................38 ...........................................................................................................................................................38 Installing the JDK...................................................................................................................................39 Installing the SDK.................................................................................................................................. ! Installing "cli#se.................................................................................................................................... 8 Installing the AD$ Pl%gin &or "cli#se...................................................................................................... 8 Con&ig%re the AD$ Pl%gin......................................................................................................................'3 (#dating the AD$ Pl%gin.......................................................................................................................' Create a #roject )ith "cli#se..................................................................................................................'* $o create an A+D,.................................................................................................................................6! -%nning Android A##lication..................................................................................................................63

(hapter 3" Application 1undamentals....................................................................//


A##lication Com#onents........................................................................................................................6*

(hapter 2" 4otifications....................................................................................5!


$oast .oti&ications.................................................................................................................................*/ Create 0o%r &irst $oast ..........................................................................................................................*3

(hapter 6" )nput (ontrols..................................................................................57


"vent 1isteners......................................................................................................................................*8 2%ttons...................................................................................................................................................83 4anage t)o 2%ttons..............................................................................................................................8 $e5t 6ields.............................................................................................................................................9! Chec7bo5es...........................................................................................................................................9' -adio 2%ttons........................................................................................................................................99 $oggle 2%ttons.....................................................................................................................................!3 S#inners...............................................................................................................................................!3* "5ercise...............................................................................................................................................!!/

Appendix A" (ompilation error...........................................................................!!3

!00

About the Author

(amilus 8aynaldo is a software de eloper with more than se en years of experience in .4et and .a a de elopment.

-ther fields of interest are" 'eb de elopment *9$:;#(SS< =:;, and oracle database. 9e graduated from the >)4?@?AA in 2002 with a 0achelor of Science degree in computer science 9e writes android applications for personal use and works as )$ Bngineering at -4) *(itiCen )dentification System in 9aiti, since 2005.

!00

Preface

$his book is intended to any person wanting to learn Android programming while gi ing to the reader the necessary foundation in Ja a and familiar with the .a a keywords used in Android. $his book was designed to pro ide the foundation for a no ice user without any prereDuisites through detailed examples using the new Android SEF *Jelly 0ean,< and as a guide to set a standard for all future android programmers.

!00

Chapter 1: Object Oriented Programming Concept

$his chapter will gi e you a brief introduction to the ob.ect concept and how you will use these ob.ects in .a a. $his chapter is not intended to teach you the Ja a language but gi es you the basics needed in this language in order to better understand Android without being an expert in .a a -b.ectGoriented programming *--P, is a programming language model organiCed around objects

Creating objects
Vehicle is an ob.ect and has a name< 0eha iors *start< Steer, ehicle gets attributes *color< wheel, and

!00

Inheritance
;etHs create new ob.ect Animal and Iehicle Automobile and Plane inherit from Iehicle< :ammal inherit from Animal

Object Animal

Object Vehicle

!00

Java Programming
Java Basic Data T !es
$here are two data types a ailable in .a a" "# Primitive Data T !es
Boolean int double String $r%th val%e 8true or false9 Integer 83: !: ; *9 -eal n%mber 83.! : !.3: ;/.!9 $e5t 8<hello=: <e5am#le=9

Iisit the http"##www.tutorialspoint.com website for a complete list of primiti e data types

$# %eference Data T !es $o create an instance of a reference type< use the ne& keyword in .a a Iehicle Jne& Iehicle

Accessors
Name P%blic Protected De&a%lt Private Description >thers can %se it Accessible &rom all classes in the same #ac7age Accessible onl0 b0 classes in the same #ac7age +ariables and methods can onl0 be accessed inside method o& the same class

!00

Architecture of a java !rogram

Java Class
A class is a blue print from which indi idual ob.ects are created. A class contains any of the following ariable types"

Ja a class defines a data type by specifying" )nstance ariables :ethods (onstructors

Instance variables

Specifies the set of alues Eeclare outside any method. Always use access modifier !rivate. ?se modifier final with instance ariables that ne er change.

public class Vehicle { public double speed;

!00

'etho(s
A Ja a method is a collection of statements that are grouped together to perform an operation. )n ob.ects created at the beginning of this chapter you can see that ob.ects ha e Behaviors< in .a a these beha iors are called methods. A method is used to define operations on instance ariables
public void speed() { // Method body }

Constructors
A constructor is used to construct an ob.ect. ) nta*
(onstructor4ame*Arguments, K ## (onstructor 0ody L

'ust have the same name of the class that the are in
class (;ASS4A:BK (;ASS4A:B*, K L L

Can have multi!le constructors !er class

!ublic class (lassname K (lassname*, K L (lassname*MA8G?:B4$SN, K L L

!00

+an(les initiali,ation of our class


(;ASS4A:B ob.!Jne& (;ASS4A:B*, (;ASS4A:B ob.2Jne& (;ASS4A:B*MA8G?:B4$SN,

A constructor ne er returns a alue (onstructor arguments can be used to initialiCe the fields in the ob.ects.

4.0 All (lasses need at least one constructor Accessing fields: object.fieldname

Creating an Object:
As mentioned pre iously a class pro ides the blueprints for ob.ects. So basically an ob.ect is created from a class. )n .a a the new key word is used to create new ob.ects. $here are three steps when creating an ob.ect from a class"

Declaration: A ariable declaration with a ariable name with an ob.ect type. Instantiation: $he OnewO key word is used to create the ob.ect. Initiali,ation: $he OnewO keyword is followed by a call o a constructor. $his call initialiCes the new ob.ect.

-*am!le "
class Puppy{ public Puppy(String name){ // This constructor has one parameter name! System!out!println("Passed #ame is $" % name ); } public static void main(String &'args){ // (ollo)ing statement )ould create an ob*ect myPuppy Puppy myPuppy + ne) Puppy( "tommy" ); } }

)f you compile and run the abo e program then it would produce following result"

!00

Passed 4ame is" tommy

Accessing Instance Variables an( 'etho(s:


)nstance ariables and methods are accessed ia created ob.ects. $o access an instance ariable the fully Dualified path should be as follows"
/, (irst create an ob*ect ,/ -b*ect.e/erence + ne) 0onstructor(); /, #o) call a variable as /ollo)s ,/ -b*ect.e/erence!variable#ame; /, #o) you can call a class method as /ollo)s ,/ -b*ect.e/erence!Method#ame();

Anatom of a class

)f you compile and run the abo e program then it would produce following result"

!00

Passed 4ame is "tommy PuppyOs age is "2 Iariable Ialue "2

4.0 -ne class is eDual to one file

Java Inheritance

)n .a a inheritance allows classes to inherit functionality from other classes )n the example below< Automobile and Plane classes are subclass of Iehicle Automobile and Plane ha e all the fields and methods that Iehicle has Automobile and Plane can add their own fields and methods Automobile and Plane can replace a parentPs method by reimplementing it

public class Vehicle { public double speed; } public class 1utomobile e2tends Vehicle { public 1utomobile() { this!speed + 34; } }

!00

)n this example< the Automobile class inherits from Iehicle< which means that the attributes speed< although defined in the class Iehicle< are present in the class Automobile. $he constructor defined in class Automobile can also initialiCe these attributes.

This
$he keyword this refers to a class< the current instance of the class itself. This can be used inside any method to refer to the current ob.ect.
public class 0alculating { protected int value; public void calculates(int value) { this!value + this!value % value; } }

)n this example< the method calculates adds the alue parameter to the attribute alue and stores the result in the attribute alue. $he attribute has been explicitly designated by the keyword this< pointing to the instance of the class< prefixed to the name of the attribute. $he this keyword can be used to pass a reference to the instance itself as a parameter of a method.

1or example" register as e ent listener" source.addlistener(this)

Note: )n an anonymous class it is necessary to repeat the class name of the ob.ect before the keyword this.

!00

)u!er
$he keyword su!er allows access to members of the superclass of a class< the same way that you can access the attributes of the class itself using the keyword this. $he su!er keyword as a standalone statement is used to call the constructor of the superclass in the base class

) nta*: )u!er.Q:ethodR4ameS " (all to a method of the super class in the base class

)tatic
$he static modifier indicates" 1or a method< it can be called without instantiating the class *s nta*: (lass.method *,,. 1or an attribute< it is a class attribute< and its alue is shared between different instances of the class.

!00

Neste( or Inner Classes


A nested class is a class that is defined inside another class 4ested classes ha e access to all members of the enclosing class< e en pri ate members. 4ested classes can be declared static 4onGstatic nested classes are called inner classes
P%blic Private Nested Classes I& 0o% )ant methods in other classes to %se it I& 0o% are onl0 going to %se it in the enclosing class

-*am!le $:

Another example with method -*am!le .:

!00

Interfaces
An interface is a specification of a class Eefines a set of method that a class must implement )nterface donPt ha e constructor )nterfaces only ha e method

Declaring Interfaces:
$he interface keyword is used to declare an interface. )nterfaces ha e the following properties"

An interface is implicitly abstract. %ou do not need to use the abstract keyword when declaring an interface. Bach method in an interface is also implicitly abstract< so the abstract keyword is not needed. :ethods in an interface are implicitly public.
inter/ace 1nimal { public void eat(); public void travel(); }

!00

Im!lementing Interfaces:
'hen a class implements an interface< you can think of the class as signing a contract< agreeing to perform the specific beha iors of the interface. )f a class does not perform all the beha iors of the interface< the class must declare itself as abstract. A class uses the im!lements keyword to implement an interface. $he implements keyword appears in the class declaration following the extends portion of the declaration
public class Mammal5nt implements 1nimal{ public void eat(){ System!out!println("Mammal eats"); } public void travel(){ System!out!println("Mammal travels"); } public int no-/6egs(){ return 4; } public static void main(String args&'){ Mammal5nt m + ne) Mammal5nt(); m!eat(); m!travel(); }

$his would produce following result"


:ammal eats :ammal tra els

'hen o erriding methods defined in interfaces there are se eral rules to be followed"

(hecked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method. $he signature of the interface method and the same return type or subtype should be maintained when o erriding the methods. An implementation class itself can be abstract and if so interface methods need not be implemented.

'hen implementation interfaces there are se eral rules"

!00

A class can implement more than one interface at a time. A class can extend only one class< but implement many interfaces. An interface can extend another interface< similarly to the way that a class can extend another class.

Anonymous )nner (lass

A class can be declared at the time of the instantiation of its parent class. $his is called Anon mous class.

-*am!le /:
Interface )nterfaceA K Ioid methodA0*,& L

class (lassA K Ioid :ethodA*)nterfaceA ), K L L

!00

Abstract Class
T An abstract class is located midway between the interfaces and classes. T Abstract classes< such as interfaces< are not instantiable. T Abstract classes are declared with the abstract modifier.

-*am!le 0:
!ublic abstract class Animal K !rotecte( String color& ##:ethod abstract voi( eat*,& !ublic voi( tra el*, K System.out.println*UAnimals tra elU,& L

!00

class 8eptile e*ten(s Animal K !ublic voi( eat*, K System.out.println*U8eptile is an animal< that is 8eptile eatU,& L L L

Pol mor!hism
Ability of ob.ects belonging to different types to respond to methods of the same name Ability to o erride functionality from extended super class Ja a handles which o erridden ersions of methods are to be executed ;etPs ha e a look at some examples

;et us look at an example.


public inter/ace Vegetarian{} public class 1nimal{} public class 7eer e2tends 1nimal implements Vegetarian{}

!00

4ow the Eeer class is considered to be polymorphic since this has multiple inheritance. 1ollowing are true for the abo e example"

A A A A

Eeer Eeer Eeer Eeer

)SGA )SGA )SGA )SGA

Animal Iegetarian Eeer -b.ect

'hen you apply the reference ariable facts to a Eeer ob.ect reference< the following declarations are legal"
Eeer d J new Eeer*,& Animal a J d& Iegetarian J d& -b.ect o J d&

If )tatement
)f *(ondition, K Statements L

-lse
)f *(ondition, K Statements L else K Statements L

!00

-lse if
if *(-4E)$)-4, K S$A$B:B4$S L else if *(-4E)$)-4, K S$A$B:B4$S L else if *(-4E)$)-4, K S$A$B:B4$S L else K S$A$B:B4$S

The s&itch )tatement:


A switch statement allows a ariable to be tested for eDuality against a list of alues. Bach alue is called a case< and the ariable being switched on is checked for each case.
Syntax"

$he syntax of enhanced for loop is"


s&itch*expression,K case alue" ##Statements brea1& ##optional case alue" ##Statements brea1& ##optional ##%ou can ha e any number of case statements. (efault" ##-ptional ##Statements

!00

$he following rules apply to a switch statement"


$he ariable used in a switch statement can only be a byte< short< int< or char. %ou can ha e any number of case statements within a switch. Bach case is followed by the alue to be compared to and a colon. $he alue for a case must be the same data type as the ariable in the switch< and it must be a constant or a literal. 'hen the ariable being switched on is eDual to a case< the statements following that case will execute until a brea statement is reached. 'hen a brea statement is reached< the switch terminates< and the flow of control .umps to the next line following the switch statement. 4ot e ery case needs to contain a break. )f no break appears< the flow of control will !all through to subseDuent cases until a break is reached. A switch statement can ha e an optional default case< which must appear at the end of the switch. $he default case can be used for performing a task when none of the cases is true. 4o break is needed in the default case.

Chapter 2: Jell Bean !eatures

Android 2.! is optimiCed to deli er AndroidOs best performance and lowest touch latency< in an effortless< intuiti e ?). $o ensure a consistent framerate< Android 2.! extends vs nc timing across all drawing and animation done by the Android framework. B erything runs in lockstep against a !/ millisecond sync heartbeat application rendering< touch e ents< screen composition< and display refresh so frames donPt get ahead or behind. Android 2.! also adds tri!le buffering in the graphics pipeline< for more consistent rendering that makes e erything feel smoother< from scrolling to paging and animations.

!00

Android 2.! reduces touch latency not only by s nchroni,ing touch to sync timing< but also by actually antici!ating where your finger will be at the time of the screen refresh. $his results in a more reacti e and uniform touch response. )n addition< after periods of inacti ity< Android applies a CP2 in!ut boost at the next touch e ent< to make sure therePs no latency. Tooling can help you get the absolute best performance out of your apps. Android 2.! is designed to work with a new tool called s strace< which collects data directly from the ;inux kernel to produce an o erall picture of system acti ities. $he data is represented as a group of ertically stacked time series graphs< to help isolate rendering interruptions and other issues.

-nhance( Accessibilit
4ew AP)s for accessibility ser ices let you handle gestures and manage accessibilit focus as the user mo es through the onGscreen elements and na igation buttons using accessibility gestures< accessories< and other input. $he $alkback system and exploreG byGtouch are redesigned to use accessibility focus for easier use and offer a complete set of AP)s for de elopers. Accessibility ser ices can link their own tutorials into the Accessibility settings< to help users configure and use their ser ices.

!00

Apps that use standard Iiew components inherit su!!ort for the new accessibility features automatically< without any changes in their code. Apps that use custom Iiews can use new accessibility node AP)s to indicate the parts of the Iiew that are of interest to accessibility ser ices.

)u!!ort for International 2sers

Bi3Directional Te*t an( Other 4anguage )u!!ort Android 2.! helps you to reach more users through support for bi3(irectional te*t in $extIiew and Bdit$ext elements. Apps can display text or handle text editing in leftG toGright or rightGtoGleft scripts. Apps can make use of new Arabic and 9ebrew locales and associated fonts. -ther types of new language support include"

Additional )ndic languages" Fannada< $elugu< and :alayalam $he new Bmo.i characters from ?nicode ersion /.0 0etter glyph support for Japanese users *renders JapaneseGspecific ersions of glyphs when system language is set to Japanese, Arabic glyphs optimiCed for 'ebIiews in addition to the Arabic glyphs for $extIiews Iertical $ext support in 'ebIiews< including 8uby $ext and additional Iertical $ext glyphs

!00

Synthetic 0old is now a ailable for all fonts that donOt ha e dedicated bold glyphs

2ser3installable 1e ma!s $he platform now supports user3installable 1e boar( ma!s< such as for additional international keyboards and special layout types. 0y default< Android 2.! includes 25 international keymaps for keyboards< including E orak. 'hen users connect a keyboard< they can go to the Settings app and select one or more keymaps that they want to use for that keyboard. 'hen typing< users can switch between keymaps using a shortcut *ctrlGspace,. %ou can create an app to !ublish a((itional 1e ma!s to the system. $he APF would include the keyboard layout resources in it< based on standard Android keymap format. $he application can offer additional keyboard layouts to the user by declaring a suitable broadcast recei er for A($)-4R@?B8%RFB%0-A8ER;A%-?$S in its manifest.

Ne& 5a s to Create Beautiful 2I

Ee elopers can create custom notification styles like those shown in the examples abo e to display rich content and actions.

!00

-*!an(able notifications
4otifications ha e long been a uniDue and popular feature on Android. Ee elopers can use them to place important or timeGbased information in front of users in the notification bar< outside of the appPs normal ?). Android 2.! brings a ma.or update to the Android notifications framework. Apps can now display larger6 richer notifications to users that can be expanded and collapsed with a pinch or swipe. 4otifications support ne& t !es of content< including photos< ha e configurable priority< and can e en include multiple actions. $hrough an impro ed notification buil(er< apps can create notifications that use a larger area< up to 26/ dp in height. $hree tem!late( notification st les are a ailable"

0ig$extStyle" a notification that includes a multiline $extIiew ob.ect. 0ig)nboxStyle" a notification that shows any kind of list such as messages< headlines< and so on. 0igPictureStyle" a notification that showcases isual content such as a bitmap.

)n addition to the templated styles< you can create your own notification styles using an remote Vie&. Apps can add up to three actions to a notification< which are displayed below the notification content. $he actions let the users respond directly to the information in the notification in alternati e ways. Such as by email or by phone call< without isiting the app. 'ith expandable notifications< apps can gi e more information to the user< effortlessly and on demand. ?sers remain in control and can longGpress any notification to get information about the sender and optionally disable further notifications from the app.

!00

App 'idgets can resiCe automatically to fit the home screen and load different content as their siCes change.

%esi,able a!! &i(gets


Android 2.! introduces impro ed App 'idgets that can automaticall resi,e< based on where the user drops them on the home screen< the siCe to which the user expands them< and the amount of room a ailable on the home screen. 4ew App 'idget AP)s let you take ad antage of this to o!timi,e our a!! &i(get content as the siCe of widgets changes. 'hen a widget changes siCe< the system notifies the host appPs widget pro ider< which can reload the content in the widget as needed. 1or example< a widget could display larger< richer graphics or additional functionality or options. Ee elopers can still maintain control o er maximum and minimum siCes and can update other widget options whene er needed. %ou can also supply separate landscape and portrait layouts for your widgets< which the system inflates as appropriate when the screen orientation changes. App widgets can now be displayed in third party launchers and other host apps through a new bind )ntent *App'idget:anager.A($)-4RAPP')EGB$R0)4E,.

!00

)im!lifie( tas1 navigation Android 2.! makes it easy for you to manage the >?pA na igation thatPs a ailable to users from inside of your apps and helps ensure a consistent experience for users. %ou can (efine the inten(e( 2! navigation for indi idual Acti ity components of your ?) by adding a new 7'4 attribute in the appPs manifest file. At run time< as Acti ities are launched< the system extracts the ?p na igation tree from the manifest file and automatically creates the ?p affordance na igation in the action bar. Ee elopers who declare ?p na igation in the manifest no longer need to manage na igation by callback at run time< although they can also do so if needed. Also a ailable is a new Tas1)tac1Buil(er class that lets you Duickly put together a synthetic task stack to start immediately or to use when an Acti ity is launched from a Pending)ntent. (reating a synthetic task stack is especially useful when users launch Acti ities from remote iews< such as from 9ome screen widgets and notifications< because it lets the de eloper pro ide a managed< consistent experience on 0ack na igation. -as animations for Activit launch %ou can use a new helper class< Activit O!tions< to create and control the animation displayed when you launch your Acti ities. $hrough the helper class< you can specify custom animation resources to be used when the acti ity is launched< or reDuest new Coom animations that start from any rectangle you specify on screen and that optionally include a thumbnail bitmap. Transitions to 4ights Out an( 8ull )creen 'o(es 4ew system ?) flags in Iiew let you to cleanly transition from a normal application ?) *with action bar< na igation bar< and system bar isible,< to Ulights out modeU *with status bar and action bar hidden and na igation bar dimmed, or Ufull screen modeU *with status bar< action bar< and na igation bar all hidden,. Ne& t !es of remoteable Vie&s Ee elopers can now use 9ri(4a out and Vie&)tub iews in 9ome screen widgets and notifications. Grid;ayout lets you structure the content of your remote iews and manage child iews alignments with a shallower ?) hierarchy. IiewStub is an in isible< CeroGsiCed Iiew that can be used to laCily inflate layout resources at runtime. 4ive &all!a!er !revie& Android 2.! makes it easier for users to fin( an( install 4ive 5all!a!ers from apps that include them. )f your app includes ;i e 'allpapers< you can now start an Acti ity *A($)-4R(9A4GBR;)IBR'A;;PAPB8, that shows the user a pre iew of the ;i e

!00

'allpaper from your own app. 1rom the pre iew< users can directly load the ;i e 'allpaper. +igher3resolution contact !hotos 'ith Android 2.!< you can store contact !hotos that are as large as :$; * :$;< making contacts e en richer and more personal. Apps can store and retrie e contact photos at that siCe or use any other siCe needed. $he maximum photo siCe supported on specific de ices may ary< so apps should <uer the built3in contacts !rovi(er at run time to obtain the max siCe for the current de ice.

Ne& In!ut T !es an( Ca!abilities


8in( out about (evices being a((e( an( remove( Apps can register to be notifie( when any new input de ices are attached< by ?S0< 0luetooth< or any other connection type. $hey can use this information to change state or capabilities as needed. 1or example< a game could recei e notification that a new keyboard or .oystick is attached< indicating the presence of a new player. =uer the ca!abilities of in!ut (evices Android 2.! includes AP)s that let apps and games take full ad antage of all input de ices that are connected and a ailable. Apps can Duery the de ice manager to enumerate all of the input de ices currently attached and learn about the capabilities of each. Control vibrator on in!ut (evices Among other capabilities< apps can now make use of any vibrator service associated with an attached input de ice< such as for %umble Pa1 controllers.

Animation an( 9ra!hics


Vs nc for a!!s Bxtending sync across the Android framework leads to a more consistent framerate and a smooth< steady ?). So that apps also benefit< Android 2.! e*ten(s vs nc timing to all drawing and animations initiated by apps. $his lets them optimiCe operations on the ?) thread and pro ides a stable timebase for synchroniCation.

!00

Apps can take ad antage of sync timing for free< through AndroidPs animation frame&or1. $he animation framework now uses sync timing to automatically handle synchroniCation across animators. 1or specialiCed uses< apps can access sync timing through AP)s exposed by a new (horeographer class. Apps can reDuest in alidation on the next sync frame a good way to schedule animation when the app is not using the animation framework. 1or more ad anced uses< apps can post a callback that the (horeographer class will run on the next frame.

Ne& animation actions an( transition t !es $he animation framework now lets you define start and end actions to take when running IiewPropertyAnimator animations< to help synchroniCe them with other animations or actions in the application. $he action can run any runnable ob.ect. 1or example< the runnable might specify another animation to start when the pre ious one finishes. %ou can also now specify that a IiewPropertyAnimator use a layer during the course of its animation. Pre iously< it was a best practice to animate complicated iews by setting up a layer prior to starting an animation and then handling an onAnimationBnd*, e ent to remo e the layer when the animation finishes. 4ow< the with;ayer*, method on IiewPropertyAnimator simplifies this process with a single method call. A new transition type in ;ayout$ransition enables you to automate animations in response to all layout changes in a IiewGroup.

Ne& T !es of Connectivit


An(roi( Beam Android 0eam is a popular 41(Gbased technology that lets users instantly share< .ust by touching two 41(Genabled phones together. )n Android 2.!< Android 0eam makes it easier to share images< ideos< or other payloads by leveraging Bluetooth for the (ata transfer. 'hen the user triggers a transfer< Android 0eam hands o er from 41( to 0luetooth< making it really easy to manage the transfer of a file from one de ice to another.

!00

5i38i Net&or1 )ervice Discover Android 2.! introduces support for multicast DN)3base( service (iscover < which lets applications find and connect to ser ices offered by peer de ices o er 'iG1i networks including mobile de ices< printers< cameras< media players< and others. Ee elopers can take ad antage of 'iG1i network ser ice disco ery to build crossGplatform or multiplayer games and application experiences. ?sing the ser ice disco ery AP)< apps can create and register any kind of ser ice< for any other 4SEGenabled de ice to disco er. $he ser ice is ad ertised by multicast across the network using a humanGreadable string identifier< which lets user more easily identify the type of ser ice. (onsumer de ices can use the AP) to scan and disco er ser ices a ailable from de ices connected to the local 'iG1i network. After disco ery< apps can use the AP) to resol e the ser ice to an )P address and port through which it can establish a socket connection. %ou can take ad antage of this AP) to build new features into your apps. 1or example< you could let users connect to a webcam< a printer< or an app on another mobile de ice that supports 'iG1i peerGtoGpeer connections. 5i38i Direct )ervice Discover )ce (ream Sandwich introduced support for 'iG1i Eirect< a technology that lets apps (iscover an( !air (irectl < o er a highGbandwidth peerGtoGpeer connection. 'iG1i Eirect is an ideal way to share media< photos< files and other types of data and sessions< e en where there is no cell network or 'iG1i a ailable. 'ith Jelly 0ean< Android takes 'iG1i Eirect further< adding AP) support for !re3 associate( service (iscover . PreGassociated ser ice disco ery lets your apps get more useful information from nearby de ices about the ser ices they support< before they attempt to connect. Apps can initiate disco ery for a specific ser ice and filter the list of disco ered de ices to those that actually support the target ser ice or application. 1or example< this means that your app could disco er only de ices that are >printersA or that ha e a specific game a ailable< instead of disco ering all nearby 'iG1i Eirect de ices. -n the other hand< your app can ad ertise the ser ice it pro ides to other de ices< which can disco er it and then negotiate a connection. $his greatly simplifies disco ery and pairing for users and lets apps take ad antage of 'iG1i Eirect more effecti ely. 'ith 'iG1i Eirect ser ice disco ery< you can create apps and multi!la er games that can share photos< ideos< gameplay< scores< or almost anything else all without

!00

reDuiring any )nternet or mobile network. %our users can connect using only a direct p2p connection< which a oids using mobile bandwidth.

Net&or1 Ban(&i(th 'anagement Android 2.! helps apps manage (ata usage appropriately when the de ice is connecte( to a metere( net&or1< including tethering to a mobile hotspot. Apps can Duery whether the current network is metered before beginning a large download that might otherwise be relati ely expensi e to the user. $hrough the AP)< you can now get a clear picture of which networks are sensiti e to data usage and manage your network acti ity accordingly.

Ne& 'e(ia Ca!abilities


'e(ia co(ec access Android 2.! pro ides lowGle el access to platform hardware and software codecs. Apps can Duery the system to disco er what lo&3level me(ia co(ecs are a ailable on the de ice and then and use them in the ways they need. 1or example< you can now create multiple instances of a media codec< Dueue input buffers< and recei e output buffers in return. )n addition< the media codec framework supports protected content. Apps can Duery for an a ailable codec that is able to play protected content with a E8: solution a ailable on the the de ice. 2)B Au(io ?S0 audio output support allows hardware endors to build hardware such as au(io (oc1s that interface with Android de ices. $his functionality is also exposed with the Android O!en Accessor Develo!ment >it *AEF, to gi e all de elopers the chance to create their own hardware. Au(io recor( triggering Android now lets you trigger au(io recor(ing based on the completion of an audio playback track. $his is useful for situations such as playing back a tone to cue your users to begin speaking to record their oices. $his feature helps you sync up recording so you donPt record audio that is currently being played back and pre ents recordings from beginning too late. 'ultichannel au(io

!00

Android 2.! supports multichannel au(io on de ices that ha e hardware multichannel audio out through the +D'I !ort. :ultichannel audio lets you deli er rich media experiences to users for applications such as games< music apps< and ideo players. 1or de ices that do not ha e the supported hardware< Android automatically downmixes the audio to the number of channels that are supported by the de ice *usually stereo,. Android 2.! also adds builtGin support for encoding#decoding AA( 6.! audio. Au(io !re!rocessing Ee elopers can apply !re!rocessing effects to audio being recorded< such as to apply noise suppression for impro ing speech recording Duality< echo cancellation for acoustic echo< and auto gain control for audio with inconsistent olume le els. Apps that reDuire high Duality and clean audio recording will benefit from these preprocessors. Au(io chaining :ediaPlayer supports chaining au(io streams together to play audio files without pauses. $his is useful for apps that reDuire seamless transitions between audio files such as music players to play albums with continuous tracks or games. 'e(ia %outer $he new AP)s :edia8outer< :edia8outeActionPro ider< and :edia8oute0utton pro ide standard mechanisms and ?) for choosing &here to !la me(ia. Support is builtGin for wired headsets and a2dp bluetooth headsets and speakers< and you can add your own routing options within your own app.

%en(erscri!t Com!utation
Android 2.! extends 8enderscript computation to gi e you more flexibility. %ou can now sam!le te*tures in your 8enderscript compute scripts< and ne& !ragmas are a ailable to define the floating point precision reDuired by your scripts. $his lets you enable N-ON instructions such as fast ector math operations on the (P? path< that wouldnPt otherwise be possible with the full )BBB 562G2007 standard. %ou can now (ebug your 8enderscript compute scripts on *?@3base( emulator an( har(&are (evices. %ou can also define multiple rootGstyle kernels in a single 8enderscript source file.

!00

An(roi( Bro&ser an( 5ebVie&


)n Android 2.!< the Android 0rowser and 'ebIiews include these enhancements"

0etter 9$:;6 ideo user experience< including touchGtoGplay#pause and smooth transition from inline to full screen mode. )mpro ed rendering speed and reduced memory usage for better scrolling and Cooming performance. )mpro ed 9$:;6#(SS3#(an as animation performance. )mpro ed text input. ?pdated Ja aScript Bngine *I7, for better Ja aScript performance. Support for the updated 9$:;6 :edia (apture specification *the UcaptureU attribute on input typeJfile elements,.

9oogle APIs an( services


$o extend the capabilities of Android e en further< se eral new ser ices for Android are a ailable. 9oogle Clou( 'essaging for An(roi( Google (loud :essaging *G(:, is a ser ice that lets de elopers send short message (ata to their users on Android de ices< without needing a proprietary sync solution. G(: handles all the details of <ueuing messages an( (elivering them efficiently to the targeted Android de ices. )t supports message multicasting and can reach up to !000 connected de ices simultaneously with a single reDuest. )t also supports message !a loa(s< which means that in addition to sending tickle messages to an app on the de ice< de elopers can send up to 2F of data.

A!! -ncr !tion Starting with Android 2.!< Google Play will help protect application assets by encrypting all paid apps with a de iceGspecific key before they are deli ered and stored on a de ice. )mart A!! 2!(ates Smart app updates is a new feature of Google Play that introduces a better way of deli ering a!! u!(ates to de ices. 'hen de elopers publish an update< Google Play now deli ers only the bits that have change( to de ices< rather than the entire APF. $his makes the updates much lighterGweight in most cases< so they are faster to

!00

download< sa e the de icePs battery< and conser e bandwidth usage on usersP mobile data plan. -n a erage< a smart app update is about "A. the si,e of a full APF update.

9oogle Pla services Bcoming soon# Google Play ser ices helps de elopers to integrate 9oogle services such as authentication and GoogleV into their apps deli ered through Google Play. Google Play ser ices will be automatically pro isioned to end user de ices by Google Play< so all you need is a thin client librar in your apps. 0ecause your app only contains the small client library< you can take ad antage of these ser ices without a big increase in download siCe and storage footprint. Also< Google Play will (eliver regular u!(ates to the ser ices< without de elopers needing to publish app updates to take ad antage of them.

!00

Installing An(roi(
$he de elopment en ironment used for the sample applications in this book includes"

:icrosoft 'indows =P#Iista#5 Ja a Ee elopment Fit *JEF, ersion / $he Android SEF a ailable for download at the Google de eloper website" http"##de eloper.android.com#sdk#index.html Bclipse )EB *)ntegrated Ee elopment Bn ironment, ersion 3.5 AE$ plugin for Bclipse

)u!!orte( O!erating ) stems 'indows =P *32Gbit,< Iista *32G or /2Gbit,< or 'indows 5 *32G or /2Gbit, :ac -S = !0.6.7 or later *x7/ only, ;inux *tested on ?buntu ;inux< ;ucid ;ynx, WG4? ( ;ibrary *glibc, 2.5 or later is reDuired. -n ?buntu ;inux< ersion 7.02 or later is reDuired. /2Gbit distributions must be capable of running 32Gbit applications.

!00

Installing the JD>


!G Eouble click the jdk-6u26-windows-x64 to launch the )nstallation 'iCard

2G (lick Ne*t

!00

3G (lick Ne*t to choose your installation folder

2G (lick Ne*t to begin the installation

!00

6G -nce the progression ended< the Product 8egistration window appears

/G (lick 8inish

Installing the )D>


!G Eouble click installer_r20.0.1-windows6 the 'elcome to the Android SEF

$ools window appears

!00

2G (lick Ne*t

3G (lick Ne*t

!00

2G (lick Ne*t

6G (lick Ne*t and choose the )nstall ;ocation

!00

/G (lick Ne*t

5G (lick Install and wait for the application to load< once completed< click Ne*t

!00

7G (lick 8inish

XG Select the package you want to install *Android 2.! AP) !/ will be used in this book,

!00

!0G (lick Install !ac1agesC

%ecommen(e( Pac1ages
9ereOs an outlines of the packages reDuired and those we recommend you use" )D> Tools %e<uire(. %our new SEF installation already has the latest ersion. :ake sure you keep this up to date. )D> Platform3tools %e<uire(. %ou must install this package when you install the SEF for the first time. )D> Platform %e<uire(. %ou need to download at least one platform into your en ironment so youOre able to compile your application. )n order to pro ide the best user experience on the latest de ices< we recommend that you use the latest platform ersion as your build target. %ouOll still be able to run your app on older ersions< but you must build against the latest ersion in order to use new features when running on de ices with the latest ersion of Android. ) stem Image %ecommen(e(. Although you might ha e one or more AndroidGpowered de ices on which to test your app< itOs unlikely you ha e a de ice for e ery ersion of Android your app supports. )tOs a good practice to download a system image for each ersion of Android you support and use them to test your app on the Android emulator. )D> )am!les %ecommen(e(. $he samples gi e you source code that you can use to learn about Android< load as a pro.ect and run< or reuse in your own app. 4ote that multiple samples

!00

packages are a ailable Y one for each Android platform ersion. 'hen you are choosing a samples package to download< select the one whose AP) ;e el matches the AP) ;e el of the Android platform that you plan to use. An(roi( )u!!ort %ecommen(e(. $he AP)s a ailable in this static library allow you to use a ariety of new framework features *including some not a ailable in e en the latest ersion, on de ices running a platform ersion as old as Android !./

!!G Select Acce!t All and Install

!2G'ait for all the packages to download and install

!00

Installing -cli!se
$o install Bclipse you must first download and extract the file in a folder< then create a shortcut of the Bclipse executable on the desktop

Installing the ADT Plugin for -cli!se


!, Eouble click on the Bclipse icon to start Bclipse for the first time

$he 'orkspace ;auncher window appears< and allows you to specify a workspace directory& you can use the default 'orkspace. 2, (lick -F< then the Bclipse welcome screen appears

!00

3, Select +el! D Install Ne& )oft&areEEEE

2, (lick A((< at the topGright corner.

!00

6, )n the Add 8epository dialog that appears< enter UAE$ PluginU for the 4ame and

the following ?8; for the ;ocation" https"##dlGssl.google.com#android#eclipse#

/, (lick O>

Note: )f you ha e trouble acDuiring the plugin< try using UhttpU in the ;ocation ?8;< instead of UhttpsU *https is preferred for security reasons,.

!00

5, )n the A ailable Software dialog< select the checkbox next to Ee eloper $ools

and click Ne*t.

7, )n the next window< youOll see a list of the tools to be downloaded. (lick Ne*t.

!00

X, 8ead and accept the license agreements< then click 8inish.

Note: )f you get a security warning saying that the authenticity or alidity of the software canOt be established< click -F. !0,'hen the installation completes< restart Bclipse.

!00

Configure the ADT Plugin


After youO e installed AE$ and restarted Bclipse< you must specify the location of your Android SEF directory" !, Select 5in(o& S PreferencesEEE to open the Preferences panel

2, Select Android from the left panel.

!00

%ou may see a dialog asking whether you want to send usage statistics to Google. )f so< make your choice and click Proceed. 1or the SEF ;ocation in the main panel< click 0rowse... and locate your downloaded Android SEF directory *such as androidGsdkGwindows,. 3, (lick A!!l then O>. )f you ha enOt encountered any errors< youOre done setting up AE$ and can continue to the next step of the SEF installation.

2!(ating the ADT Plugin


1rom time to time< a new re ision of the AE$ Plugin becomes a ailable< with new features and bug fixes. Generally< when a new re ision of AE$ is a ailable< you should update to it as soon as con enient. )n some cases< a new re ision of AE$ will ha e a dependency on a specific re ision of the Android SEF $ools. )f such dependencies exist< you will need to update the SEF $ools package of the SEF after installing the new re ision of AE$. $o update the SEF $ools package< use the Android SEF :anager< as described in Bxploring the SEF. $o learn about new features of each AE$ re ision and also any dependencies on the SEF $ools< see the listings in the 8e isions section. $o determine the ersion currently

!00

installed< open the Bclipse )nstalled Software window using +el! S )oft&are 2!(ates and refer to the ersion listed for UAndroid Ee elopment $oolsU.

1ollow the steps below to check whether an update is a ailable and< if so< to install it.
!, Select +el! S Chec1 for 2!(ates.

)f there are no updates a ailable< a dialog will say so and youOre done.
2, )f there are updates a ailable< check the one that you wish to install then click

Ne*t.

!00

3, )n the ?pdate Eetails dialog< click Ne*t.

2, 8ead and accept the license agreement and then click 8inish. $his will

download and install the latest ersion of Android EE:S and Android Ee elopment $ools.

!00

6, 8estart Bclipse.

Create a !roject &ith -cli!se


!, )n Bclipse< select 8ile S Ne& S OtherZ

!00

2, Select An(roi( A!!lication Project and click Ne*t.

3, Bnter a pro.ect name *such as U9ello 'orldU,< Select a build target. $his is the platform ersion against which you will compile your app.

Pac1age Name" $he package namespace for your app *following the same rules as packages in the Ja a programming language,. %our package name must be uniDue across all packages installed on the Android system. 1or this reason< itOs important that you use a standard domainGstyle package name thatPs appropriate to your company or publisher entity. 1or your first app< you can use something like Ucom.example.hello.world.U but in this book you are going to use FcomEAPBoo1Ea!!name F *AP0ook" Android Programming 0ook, 9owe er< you cannot publish your app using the Ucom.exampleU namespace. 'inimum )D>" Select *Android 2.2,.

!00

2, (lick Ne*t< the following window allows you to create an icon for your

application

6, (lick ChooseC to choose and icon then click Ne*t /, %ou can select whether to create an acti ity or not< check (reate Acti ity

!00

5, $he following window allows you to create a new blank acti ity

7, (lick 8inish.

!00

To create an AVD:
!, )n Bclipse< select 5in(o& S AVD 'anager< or click the AVD 'anager icon in

the Bclipse toolbar.

2, )n the Android Iirtual Ee ice :anager panel< click Ne&.

3, 1ill in the details for the AIE. Gi e it a name< a platform target< an SE card siCe< and a skin *9IGA is default,.

!00

2, (lick Create AVD.

)f you would like to display your application on tablets< you need to create other emulator that represents tablet de ice. (reate a new emulator with a '=GA700G5in skin or any other emulator skins below 'IGA700 *270x700< high density< normal screen, 'IGA762 *270x762 high density< normal screen, '=GA520 *!270x520< extraGhigh density< normal screen, 'SIGA *!022x/00< medium density< large screen, '=GA700G5in *!270x700< high density< large screen, '=GA700 *!270x700< medium density< xlarge screen,

!00

%unning An(roi( A!!lication


!, $o run *or debug, an Android application< select %un S %un *or %un S Debug, from the Bclipse menu bar< or right click the pro.ect in the package explorer %un As S An(roi( A!!lication

2, ;aunching the emulator will take a little time

!00

%esult shoul( loo1 li1e this:

Same 9ello 'orld application in a 5A tablet emulator

!00

!00

Chapter ": #pplication !undamentals

Android applications are written in the Ja a programming language. $he Android SEF tools compile the code along with any data and resource files into an Android package< an archi e file with an .apk suffix. All the code in a single .apk file is considered to be one application and is the file that AndroidGpowered de ices use to install the application.

-nce installed on a de ice< each Android application li es in its own security sandbox" $he Android operating system is a multiGuser ;inux system in which each application is a different user. 0y default< the system assigns each application a uniDue ;inux user )E *the )E is used only by the system and is unknown to the application,. $he system sets permissions for all the files in an application so that only the user )E assigned to that application can access them. Bach process has its own irtual machine *I:,< so an applicationOs code runs in isolation from other applications. 0y default< e ery application runs in its own ;inux process. Android starts the process when any of the applicationOs components need to be executed< then shuts down the process when itOs no longer needed or when the system must reco er memory for other applications.

!00

A!!lication Com!onents
Application components are the essential building blocks of an Android application. Bach component is a different point through which the system can enter your application. 4ot all components are actual entry points for the user and some depend on each other< but each one exists as its own entity and plays a specific role each one is a uniDue building block that helps define your applicationOs o erall beha ior.

$here are four different types of application components. Bach type ser es a distinct purpose and has a distinct lifecycle that defines how the component is created and destroyed. 9ere are the four types of application components"

Activities
An acti ity represents a single screen with a user interface. 1or example< an email application might ha e one acti ity that shows a list of new emails< another acti ity to compose an email< and another acti ity for reading emails. Although the acti ities work together to form a cohesi e user experience in the email application< each one is independent of the others. As such< a different application can start any one of these acti ities *if the email application allows it,. 1or example< a camera application can start the acti ity in the email application that composes new mail< in order for the user to share a picture. An acti ity is implemented as a subclass of Activit .

)ervices
A ser ice is a component that runs in the background to perform longGrunning operations or to perform work for remote processes. A ser ice does not pro ide a user interface. 1or example< a ser ice might play music in the background while the user is in a different application< or it might fetch data o er the network without blocking user interaction with an acti ity. Another component< such as an acti ity< can start the ser ice and let it run or bind to it in order to interact with it. A ser ice is implemented as a subclass of )ervice.

Content !rovi(ers
A content pro ider manages a shared set of application data. %ou can store the data in the file system< an S@;ite database< on the web< or any other persistent storage location your application can access. $hrough the content pro ider< other applications

!00

can Duery or e en modify the data *if the content pro ider allows it,. 1or example< the Android system pro ides a content pro ider that manages the userOs contact information. As such< any application with the proper permissions can Duery part of the content pro ider *such as (ontacts(ontract.Eata, to read and write information about a particular person. (ontent pro iders are also useful for reading and writing data that is pri ate to your application and not shared. A content pro ider is implemented as a subclass of ContentProvi(er and must implement a standard set of AP)s that enable other applications to perform transactions.

Broa(cast receivers
A broadcast recei er is a component that responds to systemGwide broadcast announcements. :any broadcasts originate from the system for example< a broadcast announcing that the screen has turned off< the battery is low< or a picture was captured. Applications can also initiate broadcasts for example< to let other applications know that some data has been downloaded to the de ice and is a ailable for them to use. Although broadcast recei ers donOt display a user interface< they may create a status bar notification to alert the user when a broadcast e ent occurs. :ore commonly< though< a broadcast recei er is .ust a UgatewayU to other components and is intended to do a ery minimal amount of work. 1or instance< it might initiate a ser ice to perform some work based on the e ent. A broadcast recei er is implemented as a subclass of Broa(cast%eceiver and each broadcast is deli ered as an )ntent ob.ect. A uniDue aspect of the Android system design is that any application can start another applicationPs component. 1or example< if you want the user to capture a photo with the de ice camera< thereOs probably another application that does that and your application can use it< instead of de eloping an acti ity to capture a photo yourself. %ou donOt need to incorporate or e en link to the code from the camera application. )nstead< you can simply start the acti ity in the camera application that captures a photo. 'hen complete< the photo is e en returned to your application so you can use it. $o the user< it seems as if the camera is actually a part of your application. 'hen the system starts a component< it starts the process for that application *if itOs not already running, and instantiates the classes needed for the component. 1or example< if your application starts the acti ity in the camera application that captures a photo< that acti ity runs in the process that belongs to the camera application< not in your applicationOs process. $herefore< unlike applications on most

!00

other systems< Android applications donOt ha e a single entry point *thereOs no main*, function< for example,. 0ecause the system runs each application in a separate process with file permissions that restrict access to other applications< your application cannot directly acti ate a component from another application. $he Android system< howe er< can. So< to acti ate a component in another application< you must deli er a message to the system that specifies your intent to start a particular component. $he system then acti ates the component for you.

Activating Com!onents
$hree of the four component types< activities< services< and broa(cast receivers are acti ated by an asynchronous message called intent. )ntents bind indi idual components to each other at runtime *you can think of them as the messengers that reDuest an action from other components,< whether the component belongs to your application or another. An intent is created with an )ntent ob.ect< which defines a message to acti ate either a specific component or a specific type of component an intent can be either explicit or implicit< respecti ely. 1or acti ities and ser ices< an intent defines the action to perform *for example< to U iewU or UsendU something, and may specify the ?8) of the data to act on *among other things that the component being started might need to know,. 1or example< an intent might con ey a reDuest for an acti ity to show an image or to open a web page. )n some cases< you can start an acti ity to recei e a result< in which case< the acti ity also returns the result in an )ntent *for example< you can issue an intent to let the user pick a personal contact and ha e it returned to you the return intent includes a ?8) pointing to the chosen contact,. 1or broadcast recei ers< the intent simply defines the announcement being broadcast *for example< a broadcast to indicate the de ice battery is low includes only a known action string that indicates Ubattery is lowU,. $he other component type< content !rovi(er< is not acti ated by intents. 8ather< it is acti ated when targeted by a reDuest from a (ontent8esol er. $he content resol er handles all direct transactions with the content pro ider so that the component thatOs performing transactions with the pro ider doesnOt need to and instead calls methods on the (ontent8esol er ob.ect. $his lea es a layer of abstraction between the content pro ider and the component reDuesting information *for security,. $here are separate methods for acti ating each type of component"

!00

%ou can start an acti ity *or gi e it something new to do, by passing an )ntent to startActi it!"# or startActi it!$or%esult"# *when you want the acti ity to return a result,. %ou can start a ser ice *or gi e new instructions to an ongoing ser ice, by passing an )ntent to start&er ice"#. -r you can bind to the ser ice by passing an )ntent to bind&er ice"#. %ou can initiate a broadcast by passing an )ntent to methods like send'roadcast"#< send(rdered'roadcast"#< or send&tick!'roadcast"#. %ou can perform a Duery to a content pro ider by calling )uer!"# on a (ontent8esol er.

The 'anifest 8ile


0efore the Android system can start an application component< the system must know that the component exists by reading the applicationOs Android:anifest.xml file *the UmanifestU file,. %our application must declare all its components in this file< which must be at the root of the application pro.ect directory. $he manifest does a number of things in addition to declaring the applicationOs components< such as" )dentify any user permissions the application reDuires< such as )nternet access or readGaccess to the userOs contacts. Eeclare the minimum AP) ;e el reDuired by the application< based on which AP)s the application uses. Eeclare hardware and software features used or reDuired by the application< such as a camera< bluetooth ser ices< or a multitouch screen. AP) libraries the application needs to be linked against *other than the Android framework AP)s,< such as the Google :aps library.

!00

Chapter $: Notifications

Se eral types of situations may arise that reDuire you to notify the user about an e ent that occurs in your application. Some e ents reDuire the user to respond and others do not. 1or example" o 'hen an e ent such as sa ing a file is complete< a small message should appear to confirm that the sa e was successful. o )f the application is running in the background and needs the userOs attention< the application should create a notification that allows the user to respond at his or her con enience. o )f the application is performing work that the user must wait for *such as loading a file,< the application should show a ho ering progress wheel or bar. Bach of these notification tasks can be achie ed using a different techniDue"
o o o

A $oast 4otification< for brief messages that come from the background. A Status 4otification< for persistent reminders that come from the background and reDuest the userOs response. A Eialog 4otification< for Acti ityGrelated notifications.

!00

Note: )n this book you will use the toast notification

Toast Notifications
A toast notification is a message that pops up on the surface of the window. )t only fills the amount of space reDuired for the message and the userOs current acti ity remains isible and interacti e. $he notification automatically fades in and out< and does not accept interaction e ents. $he class toast is in the package an(roi(E&i(get $ables below present methods and constants of the class toast.

Class Toast
Constants int int %&N'()*%ON' %&N'()*S)O+( Sho) the vie) or te5t noti&ication &or a long #eriod o& time. Sho) the vie) or te5t noti&ication &or a short #eriod o& time.

Public ,ethods int getDuration-.: -et%rn the d%ration. int get'ra/it -.: ?et the location at )hich the noti&ication sho%ld a##ear on the screen. static $oast ma0e(e1t-Conte1t conte1t2 int res3d2 int duration. 4a7e a standard toast that j%st contains a te5t vie) )ith the te5t &rom a reso%rce. static $oast ma0e(e1t-Conte1t conte1t2 CharSe4uence te1t2 int duration. 4a7e a standard toast that j%st contains a te5t vie). void set(e1t-int res3d. (#date the te5t in a $oast that )as #revio%sl0 created %sing one o& the ma7e$e5t89 methods. void set(e1t-CharSe4uence s. (#date the te5t in a $oast that )as #revio%sl0 created %sing one o& the ma7e$e5t89 methods. void sho5-. Sho) the vie) &or the s#eci&ied d%ration.

!00

Create our first Toast


!; (reate a new pro.ect and name it 1irst $oast /; Select the src folder< expand it< next expand the package and double click the :ainActi ity..a a

3; 9ere is how to make a toast a9 1irst< instantiate a $oast ob.ect with the make$ext*, method ma1eTe*tBConte*t conte*t6 Char)e<uence te*t6 int (uration# $his method takes three parameters" the application (ontext< the text message< and the duration for the toast. )t returns a properly initialiCed $oast ob.ect b9 Eisplay the toast notification with the show*, method -*am!le @
$oast toast J $oast.ma e"e#t*this< U1irst toast [U< $oast.$%&'"()$*&',& $oast. sho)() &

%ou can also chain your methods and a oid holding on to the $oast ob.ect< like this"
$oast toast J $oast.ma e"e#t*this< U1irst toast[U<$oast.$%&'"()$*&',.show*,&

Acti ity which hosts the toast is the :ain Acti ity hence the t*is< our (harSeDuence text is U1irst toast[U< and the duration of the toast
$oast.$%&'"()$*&'.

2G Add the toast in your 1irst$oast pro.ect

:ainActi ity..a a should look like this"

!00

!ac1age com.example.firsttoast& im!ort android.os.0undle& im!ort android.app.Acti ity& im!ort android.widget.$oast& !ublic class :ainActi ity e*ten(s Acti ity K +- erride !ublic voi( on(reate*0undle sa ed)nstanceState, K su!er.on(reate*sa ed)nstanceState,& set(ontentIiew*8.layout.activity)main,& Toast toast G ToastEmake+extBthis6 H8irst ToastH6 ToastE,-./+0_,(./#I toastEsho&B#I L L

Note: $oast.;B4G$9R;-4G " Eisplay the toast for 6 seconds $oast. ;B4G$9RS9-8$ " Eisplay the toast for 3 seconds

6G 8un the application

8esult should look something like this"

!00

)f you decide that the toast should appear at the topGleft corner< you can set the gra ity like this"
toast.setGra ity*Gra ity."*+\Gra ity.$%,"< 0< 60,&

%esult shoul( loo1 li1e this:

!00

%ou can change the toast position as you wish with the setGra ity*int< int< int, method.

!00

Im!ortant
$he examples in the book ha e been made in portrait mode< if you want to switch from portrait to ;andscape it is possible that the interface of your application is disturbed. $he purpose of this book is not to teach you to create graphical user interfaces. )f you want to learn how to create =:; interfaces for your applications< you can get the book Android ?) Eesign with =:; from same author on AmaCon.

Findle " http"##www.amaCon.com#dp#0005S-?27 2

Paperback http"##www.amaCon.com#dp# !256!220/5

!00

Chapter 6: 3nput Controls

-vent 4isteners
An e ent listener is an interface in the Vie& class that contains a single callback method. $hese methods will be called by the Android framework when the Iiew to which the listener has been registered is triggered by user interaction with the item in the ?).

)ncluded in the e ent listener interfaces are the following callback methods" onClic1B# 1rom Iiew.-n(lick;istener" $his is called when the user either touches the item *when in touch mode,< or focuses upon the item with the na igationGkeys or trackball and presses the suitable UenterU key or presses down on the trackball. on4ongClic1B# 1rom Iiew.-n;ong(lick;istener" $his is called when the user either touches and holds the item *when in touch mode,< or focuses upon the item with the na igationGkeys or trackball and presses and holds the suitable UenterU key or presses and holds down on the trackball *for one second,. on8ocusChangeB# 1rom Iiew.-n1ocus(hange;istener" $his is called when the user na igates onto or away from the item< using the na igationGkeys or trackball. on>e B# 1rom Iiew.-nFey;istener" $his is called when the user is focused on the item and presses or releases a hardware key on the de ice. onTouchB#

!00

1rom Iiew.-n$ouch;istener" $his is called when the user performs an action Dualified as a touch e ent< including a press< a release< or any mo ement gesture on the screen *within the bounds of the item,. onCreateConte*t'enuB# 1rom Iiew.-n(reate(ontext:enu;istener" $his is called when a (ontext :enu is being built *as the result of a sustained Ulong clickU,.

!00

Buttons
A button consists of text or an icon *or both text and an icon, that communicates what action occurs when the user touches it.
!G (reate a new pro.ect and name it OneButton 2G (reate the xml layout *see Android -. design with /0$ on Ama1on)

activit JmainE*ml
Q8elati e;ayout xmlns"androidJ2http344schemas.android.com4ap 4res4android2 xmlns"toolsJ2http344schemas.android.com4tools2 android"layoutRwidthJ2match)parent2 android"layoutRheightJ2match)parent2 S Q0utton android"idJ256id4button12 android"layoutRwidthJ2!ill)parent2 android"layoutRheightJ2wrap)content2 android"textJ25string4button12S Q#0uttonS Q#8elati e;ayoutS

)tringE*ml
QresourcesS Qstring nameJ2app)name2S-ne0uttonQ#stringS Qstring nameJ2hello)world2S9ello world[Q#stringS Qstring nameJ2menu)settings2SSettingsQ#stringS Qstring nameJ2title)activity)main2S:ainActi ityQ#stringS Qstring nameJ2button12S(lick :eQ#stringS Q#resourcesS

3G -pen the :ainActi ity..a a


2G Eelete the option menu code 6G Add the line im1ort.widget.'utton

!00

/G Get references to the 0utton created in activit Jmain.xml

5G Attach 0utton;isteners to the 0utton< to do this call setonclick;istener method

7G 8espond to click using the method onClic1BVie& v# by showing a toast

4isting 03"
!ac1age com.AP0ook.onebutton& im!ort android.os.0undle& im!ort android.app.Acti ity& im!ort android. iew.Iiew& im!ort android.widget.0utton& im!ort android.widget.$oast& !ublic class :ainActi ity e*ten(s Acti ity im!lements Iiew.-n(lick;istenerK

!00

+- erride !ublic voi( on(reate*0undle sa ed)nstanceState, K su!er.on(reate*sa ed)nstanceState,& set(ontentIiew*8.layout.activity)main,& 0utton button!J*0utton, findIiew0y)d*8.id.button1,& button!.set-n(lick;istener*this,& L !ublic voi( on(lick*Iiew , K $oast toast J $oast.ma e"e#t*this< U(lick[ (lick[ (lick[U< $oast.$%&'"()$*&',& toast.show*,& L L

Note: if running the application gi es you error< go to compilation error at the FA!!en(i* AK

+an(ling -vents b )!ecif ing the -vent +an(ler 'etho( in the *ml la out
!G (reate a new pro.ect and name it 0utton2
2G (reate the xml layout *see Android -. design with /0$ on Ama1on)

)n acti ityRmain.xml file created in the pro.ect called -ne0utton< add the attribute an(roi(: onClic1 to your button element< acti ityRmain.xml becomes"

Q8elati e;ayout xmlns"androidJ2http344schemas.android.com4ap 4res4android2 xmlns"toolsJ2http344schemas.android.com4tools2 android"layoutRwidthJ2match)parent2 android"layoutRheightJ2match)parent2 S Q0utton android"idJ256id4button12 android"layoutRwidthJ2!ill)parent2 android"layoutRheightJ2wrap)content2 android"textJ25string4button12 android"on(lickJ2clic 0e2S Q#0uttonS Q#8elati e;ayoutS

3G -pen the :ainActi ity..a a


2G 8esponding to (lick B ents by implementing the click:e*, method in your

acti ity

!00

!ublic voi( click:e *Iiew iew, K $oast toast J $oast.ma e"e#t*this< U(lick[ (lick[ (lick[U< $oast.$%&'"()$*&',& toast.show*,&

L L

6G 8un the application

Note: $he method you declare in the an(roi(:onClic1 attribute must ha e a signature exactly as shown abo e. Specifically< the method must" 0e public 8eturn oid Eefine a Iiew as its only parameter *this will be the Iiew that was clicked,

4isting 03$
!ac1age com.AP0ook.button2& im!ort android.os.0undle& im!ort android.app.Acti ity& im!ort android. iew.Iiew& im!ort android.widget.$oast& !ublic class :ainActi ity e*ten(s Acti ity K +- erride !ublic voi( on(reate*0undle sa ed)nstanceState, K su!er.on(reate*sa ed)nstanceState,& set(ontentIiew*8.layout.activity)main,& L !ublic voi( click:e *Iiew iew, K $oast toast J $oast.ma e"e#t*this< U(lick[ (lick[ (lick[U< $oast.$%&'"()$*&',& toast.show*,& L L

!00

4ow you ha e to choose which method to use< OnClic14istener or an(roi(:onClic1

'anage t&o Buttons


!G (reate a new pro.ect and name it T&oButton 2G (reate the xml layout *see Android -. design with /0$ on Ama1on)

Activit JmainE*ml
Q;inear;ayout xmlns"androidJ2http344schemas.android.com4ap 4res4android2 xmlns"toolsJ2http344schemas.android.com4tools2 android"orientationJ2vertical2 android"layoutRwidthJ2match)parent2 android"layoutRheightJ2match)parent2 S Q0utton android"idJ256id4button12 android"layoutRwidthJ2!ill)parent2 android"layoutRheightJ2wrap)content2 android"textJ25string4button12S Q#0uttonS Q0utton android"idJ256id4button22 android"layoutRwidthJ2!ill)parent2 android"layoutRheightJ2wrap)content2

!00

android"textJ25string4button22S Q#0uttonS Q#;inear;ayoutS

)tringsE*ml
QresourcesS Qstring nameJ2app)name2S$wo0uttonQ#stringS Qstring nameJ2hello)world2S9ello world[Q#stringS Qstring nameJ2menu)settings2SSettingsQ#stringS Qstring nameJ2title)activity)main2S:ainActi ityQ#stringS Qstring nameJ2button12SSubmitQ#stringS Qstring nameJ2button22S(ancelQ#stringS Q#resourcesS

3G -pen the :ainActi ity..a a


2G Add the line import.widget.0utton 6G Eeclare two ariables of type 0utton< ] Submit ^ and ] (ancel ^ /G Get references to the Submit 0utton created in acti ityRmain.xml

submitJ*0utton, findIiew0y)d*8.id.button1,&

5G Attach 0utton;isteners to the Submit 0utton< to do this call setonclick;istener

method

submit.set-n(lick;istener*this,&

7G Get references to the (ancel 0utton created in acti ityRmain.xml

cancelJ*0utton, findIiew0y)d*8.id.button2,&

XG Attach 0utton;isteners to the (ancel 0utton< to do this call setonclick;istener

method

!00

cancel.set-n(lick;istener*this,&

!0G 8espond to click using the onClic1BVie& v# method by showing a toast

4isting 03.
!ac1age com.AP0ook.twobutton& im!ort android.os.0undle& im!ort android.app.Acti ity& im!ort android. iew.Iiew& im!ort android.widget.0utton& im!ort android.widget.$oast& !ublic class :ainActi ity e*ten(s Acti ity im!lements Iiew.-n(lick;istenerK 0utton submit& 0utton cancel& +- erride !ublic voi( on(reate*0undle sa ed)nstanceState, K su!er.on(reate*sa ed)nstanceState,& set(ontentIiew*8.layout.activity)main,& submitJ*0utton, findIiew0y)d*8.id.button1,& submit.set-n(lick;istener*this,& cancelJ*0utton, findIiew0y)d*8.id.button2,& cancel.set-n(lick;istener*this,& L !ublic voi( on(lick*Iiew , K if * JJsubmit,K $oast toast J $oast.ma e"e#t*this< USubmit sucessfullyU< $oast.$%&'"()$*&',& toast.show*,& L else K L L L $oast toast J $oast.ma e"e#t*this< U(ancelledU< $oast.$%&'"()$*&',& toast.show*,&

!00

'anage t&o Buttons using anon mous class


See Anonymous inner class in chapter ! $he same anonymous class example in (hapter ! will be used this time with android class< interfaces< and methods.

)nterface OnClic14istener K Ioid onClic1B#

!00

L (lass Vie& K Ioid set-n(lick;istener*-n(lick;istener, K L L

Note: you can download android packages used for this book in http"##keroob.com#index.php#andro website.

4isting 03/
!ac1age com.AP0ook.button.anonymous& im!ort im!ort im!ort im!ort im!ort im!ort android.os.0undle& android.app.Acti ity& android. iew.Iiew& android.widget.0utton& android.widget.$oast& android. iew.Iiew.-n(lick;istener&

!ublic class :ainActi ity e*ten(s Acti ity K !rivate 0utton button!& !rivate 0utton button2& +- erride

!00

!ublic voi( on(reate*0undle sa ed)nstanceState, K su!er.on(reate*sa ed)nstanceState,& set(ontentIiew*8.layout.activity)main,& button!J*0utton,findIiew0y)d*8.id.button1,& button!.set-n(lick;istener*ne& -n(lick;istener *,K !ublic voi( on(lick *Iiew iew, K $oast.ma e"e#t*:ainActi ity.this<USubmit sucessfullyU< $oast.$%&'"()$*&',.show*,& L L,& button2J*0utton,findIiew0y)d*8.id.button2,& button2.set-n(lick;istener*ne& -n(lick;istener *,K !ublic voi( on(lick *Iiew iew, K $oast.ma e"e#t*:ainActi ity.this<U(ancelledU< $oast.$%&'"()$*&',.show*,& L L,& L

9ere is the result obtained using either one of these methods"

!00

!00

Te*t 8iel(s
A text field allows the user to type text into your app. )t can be either single line or multiGline. $ouching a text field places the cursor and automatically displays the keyboard

%ou can add a text field to your layout with the Bdit$ext ob.ect. %ou should usually do so in your =:; layout with an QBdit$extS element.

!G (reate a new pro.ect and name it Te*t8iel( 2G (reate the xml layout *see Android -. design with /0$ on Ama1on)

Activit JmainE*ml
Q;inear;ayout xmlns"androidJ2http344schemas.android.com4ap 4res4android2 xmlns"toolsJ2http344schemas.android.com4tools2 android"orientationJ2vertical2 android"layoutRwidthJ2match)parent2 android"layoutRheightJ2match)parent2 S Q$extIiew android"textJ25string4value2 android"idJ256id4"#t12 android"layoutRwidthJ2wrap)content2 android"layoutRheightJ2wrap)content2S Q#$extIiewS QBdit$ext android"input$ypeJ22 android"idJ256id4%dit"e#t)7alue2 android"layoutRwidthJ2200dp2 android"layoutRheightJ2wrap)content2S Q#Bdit$extS Q0utton android"textJ25string4btn2 android"idJ256id4button12 android"layoutRwidthJ2!ill)parent2 android"layoutRheightJ2wrap)content2 android"layoutRmargin$opJ212sp2S Q#0uttonS Q#;inear;ayoutS

!00

)tringsE*ml
QresourcesS Qstring nameJ2app)name2S$ext1ieldQ#stringS Qstring nameJ2hello)world2S9ello world[Q#stringS Qstring nameJ2menu)settings2SSettingsQ#stringS Qstring nameJ2title)activity)main2S:ainActi ityQ#stringS Qstring nameJ2value2SBnter your ?sernameQ#stringS Qstring nameJ2btn2SSubmitQ#stringS Q#resourcesS

3G -pen the :ainActi ity..a a 2G Add the lines >import android.widget.0uttonA< >import android.widget.Bdit$extA< >import android. iew.Iiew.-n(lick;istenerA

6G Eeclare ! ariable of type 0utton >button!A et ! ariable of type Bdit$ext >Bdit$extRIalueA

/G Get references to the 0utton created in activit JmainE*ml button!J *0utton,findIiew0y)d*8.id.button1,& Attach 0utton;isteners to the 0utton< to do this call setonclick;istener*, method *see anonymous class in chapter1) button!.set-n(lick;istener*,

5G 8espond to click using the method onClic1BVie& v#

7G Get references to the Bdit$ext created in acti ityRmain.xml Bdit$extRIalueJ*Bdit$ext,findIiew0y)d*8.id.%dit"e#t)7alue,&

XG Add the method get+ext"# which return the text the $extIiew is displaying

!00

!0G Show a toast that return the user input


4isting 030
!ac1age com.AP0ook.textfield& im!ort im!ort im!ort im!ort im!ort im!ort im!ort android.app.Acti ity& android.os.0undle& android.widget.0utton& android.widget.Bdit$ext& android.widget.$oast& android. iew.Iiew& android. iew.Iiew.-n(lick;istener&

!ublic class :ainActi ity e*ten(s Acti ity K !rivate 0utton button!& !rivate Bdit$ext Bdit$extRIalue& +- erride !ublic voi( on(reate*0undle sa ed)nstanceState, K su!er.on(reate*sa ed)nstanceState,& set(ontentIiew*8.layout.activity)main,& button!J*0utton,findIiew0y)d*8.id.button1,& button!.set-n(lick;istener*ne& -n(lick;istener *,K !ublic voi( on(lick *Iiew iew, K Bdit$extRIalueJ*Bdit$ext,findIiew0y)d*8.id.%dit"e#t)7alue,& String ?ser4ame J Bdit$extRIalue.get$ext*,.toString*,& $oast.ma e"e#t*:ainActi ity.this<U'elcome UV?ser4ame< $oast.$%&'"()$*&',.show*,& L L,& L L

!00

!00

Chec1bo*es
(heckboxes allow the user to select one or more options from a set. $ypically< you should present each checkbox option in a ertical list. $o create each checkbox option< create a (heck0ox in your layout. 0ecause a set of checkbox options allows the user to select multiple items< each checkbox is managed separately and you must register a click listener for each one.

Com!oun(Button class A button with two states< checked and unchecked. 'hen the button is pressed or clicked< the state changes automatically.
!G (reate a new pro.ect and name it Chec1Bo*es -*am!le 2G (reate the xml layout *see Android -. design with /0$ on Ama1on)

activit JmainE*ml
Q;inear;ayout xmlns"androidJ2http344schemas.android.com4ap 4res4android2 android"orientationJ2vertical2 android"layoutRwidthJ2!ill)parent2 android"layoutRheightJ2!ill)parent2S Q(heck0ox android"idJ256id4chec bo#)orange2 android"layoutRwidthJ2wrap)content2 android"layoutRheightJ2wrap)content2 android"textJ25string4orange2 #S Q(heck0ox android"idJ256id4chec bo#)apricot2 android"layoutRwidthJ2wrap)content2 android"layoutRheightJ2wrap)content2 android"textJ25string4apricot2 #S Q#;inear;ayoutS

)tringsE*ml

!00

QresourcesS Qstring nameJ2app)name2S(heck0oxes BxampleQ#stringS Qstring nameJ2hello)world2S9ello world[Q#stringS Qstring nameJ2menu)settings2SSettingsQ#stringS Qstring nameJ2title)activity)main2S:ainActi ityQ#stringS Qstring nameJ2orange2S-rangeQ#stringS Qstring nameJ2apricot2SApricotQ#stringS Q#resourcesS

3G -pen the :ainActi ity..a a

2G Add the line >import android.widget.(heck0oxA< >import

android.widget.(ompound0utton&A

6G Eeclare 2 ariables of type (heck0ox

(heck0ox (hkR-range& (heck0ox (hkRApricot&


/G Get references to the (hkR-range (heck0ox created in activit JmainE*ml

(hkR-rangeJ*(heck0ox, findIiew0y)d*8.id.chec bo#)orange,&

5G Attach ;istener to the (hkR-range checkbox< to do this call

setOnChec1e(Change4istener method

7G Get references to the (hkRApricot (heck0ox created in activit JmainE*ml XG Attach ;istener to the (hkRApricot (heckbox< to do this call

set-n(hecked(hange;istener method

!0G 8espond to click using the method onChec1e(Change( *(ompound0utton

buttonIiew< boolean is(hecked, see Table ""

!00

!!G 8espond to click on each (heck0ox by showing $oast saying which one was

(hecked.

4isting 03@
!ac1age com.AP0ook.checkboxesexample& im!ort im!ort im!ort im!ort im!ort android.os.0undle& android.app.Acti ity& android.widget.(heck0ox& android.widget.(ompound0utton& android.widget.$oast&

!ublic class :ainActi ity e*ten(s Acti ity im!lements (ompound0utton.-n(hecked(hange;istenerK (heck0ox (hkR-range& (heck0ox (hkRApricot& +- erride !ublic voi( on(reate*0undle sa ed)nstanceState, K su!er.on(reate*sa ed)nstanceState,& set(ontentIiew*8.layout.activity)main,& (hkR-rangeJ*(heck0ox, findIiew0y)d*8.id.chec bo#)orange,& (hkR-range.set-n(hecked(hange;istener*this,& (hkRApricotJ*(heck0ox, findIiew0y)d*8.id.chec bo#)apricot,& (hkRApricot.set-n(hecked(hange;istener*this,& L !ublic voi( on(hecked(hanged*(ompound0utton buttonIiew< boolean is(hecked,K if *buttonIiewJJ(hkR-range,K if *is(hecked,K $oast.ma e"e#t*:ainActi ity.this<U-range checkedU< $oast.$%&'"()$*&',.show*,& L else K $oast.ma e"e#t*:ainActi ity.this<U-range unchekedU< $oast.$%&'"()$*&',.show*,&

!00

L L else K if *is(hecked,K $oast.ma e"e#t*this<UApricot checkedU< $oast.$%&'"()$*&',.show*,& L else K $oast.ma e"e#t*this<UApricot uncheckedU< $oast.$%&'"()$*&',.show*,& L L L L

%esult shoul( loo1 li1e this:

!00

%a(io Buttons
!G (reate a new pro.ect and name it %a(ioButtons -*am!le 2G (reate the xml layout *see Android -. design with /0$ on Ama1on)

activit JmainE*ml

Q;inear;ayout xmlns"androidJ2http344schemas.android.com4ap 4res4android2 xmlns"toolsJ2http344schemas.android.com4tools2 android"layoutRwidthJ2!ill)parent2 android"layoutRheightJ2!ill)parent2 android"orientationJ2vertical2S Q;inear;ayout android"layoutRmargin$opJ228sp2 android"orientationJ2hori1ontal2 android"layoutRwidthJ2!ill)parent2 android"layoutRheightJ2wrap)content2 S Q$extIiew android"textJ25string4value2 android"idJ256id4"e#t7iew9tring2 android"layoutRwidthJ2!ill)parent2 android"layoutRheightJ2wrap)content2 android"gra ityJ2center2S Q#$extIiewS Q#;inear;ayoutS Q8adioGroup xmlns"androidJ2http344schemas.android.com4ap 4res4android2 android"idJ256id4radio)temperature2 android"layoutRwidthJ2!ill)parent2 android"layoutRheightJ2wrap)content2

!00

android"orientationJ2vertical2 android"padding$opJ220sp2 android"padding;eftJ2100sp2S Q8adio0utton android"idJ256id4radio)!arenheit2 android"layoutRwidthJ2wrap)content2 android"layoutRheightJ2wrap)content2 android"text(olorJ2:,;0<0<2 android"textJ25string4radio12 #S Q8adio0utton android"idJ256id4radio)celcius2 android"layoutRwidthJ2wrap)content2 android"layoutRheightJ2wrap)content2 android"textJ25string4radio22 #S Q#8adioGroupS Q#;inear;ayoutS

)tringsE*ml
QresourcesS Qstring nameJ2app)name2S8adio0uttons BxampleQ#stringS Qstring nameJ2hello)world2S9ello world[Q#stringS Qstring nameJ2menu)settings2SSettingsQ#stringS Qstring nameJ2title)activity)main2S:ainActi ityQ#stringS Qstring nameJ2value2S$emperature (on erterQ#stringS Qstring nameJ2radio12S(elciusQ#stringS Qstring nameJ2radio22S1ahrenheitQ#stringS Q#resourcesS

3G -pen the :ainActi ity..a a

2G Add the lines >import android.widget.8adio0uttonA< >import

android.widget.8adioGroup&A

6G Eeclare ! ariables of type 8adioGroup *rdgRtemperature, and 2 ariables of

type 8adio0utton *rdRfarenheit< rdRcelcius,

/G Get references to the 8adioGroup created in activit JmainE*ml

rdgRtemperatureJ*8adioGroup,findIiew0y)d*8.id.radio)temperature,&

!00

5G Attach ;istener to the rdgRtemperature 8adioGroup< to do this call

set-n(hecked(hange;istener*, method

7G Get references to the 8adio0uttons created in acti ityRmain.xml

rdRfarenheitJ*8adio0utton,findIiew0y)d*8.id.radio)!arenheit,& rdRcelciusJ*8adio0utton,findIiew0y)d*8.id.radio)celcius,&

XG 8espond to click using the method onChec1e(Change( *8adioGroup group< int

checked)d,

!0GShow a toast saying which 8adio0utton was checked

4isting 03:
!ac1age com.AP0ook.radiobuttonsexample& im!ort im!ort im!ort im!ort im!ort android.app.Acti ity& android.os.0undle& android.widget.8adio0utton& android.widget.8adioGroup& android.widget.$oast&

!ublic class :ainActi ity e*ten(s Acti ity K 8adioGroup rdgRtemperature& 8adio0utton rdRfarenheit& 8adio0utton rdRcelcius& +- erride

!00

!ublic voi( on(reate*0undle sa ed)nstanceState, K su!er.on(reate*sa ed)nstanceState,& set(ontentIiew*8.layout.activity)main,& rdgRtemperatureJ*8adioGroup,findIiew0y)d*8.id.radio)temperature,& rdRfarenheitJ*8adio0utton,findIiew0y)d*8.id.radio)!arenheit,& rdRcelciusJ*8adio0utton,findIiew0y)d*8.id.radio)celcius,& rdgRtemperature.set-n(hecked(hange;istener*ne& 8adioGroup.-n(hecked(hange;istener*, K !ublic voi( on(hecked(hanged*8adioGroup group< int checked)d, K if **8adio0utton,findIiew0y)d*checked)d,JJrdRfarenheit,K $oast.ma e"e#t*:ainActi ity.this<U(elcius (heckedU< $oast.$%&'"()9(*R",.show*,& L elseK $oast.ma e"e#t*:ainActi ity.this<U1arenheit (heckedU< $oast.$%&'"()9(*R",.show*,& L L L,& L L

%esult shoul( loo1 li1e this:

!00

!00

Toggle Buttons
A toggle button allows the user to change a setting between two states.

%ou can add a basic toggle button to your layout with the $oggle0utton ob.ect. Android 2.0 *AP) le el !2, introduces another kind of toggle button called a switch that pro ides a slider control< which you can add with a Switch ob.ect.

$he $oggle0utton and Switch controls are subclasses of (ompound0utton and function in the same manner< so you can implement their beha ior the same way. (reate a new pro.ect and name it )&itch Button in min sdk put 2.0 AP) le el !2

!G (reate a new pro.ect and name it )&itch Button 2G (reate the xml layout *see Android -. design with /0$ on Ama1on)

activit JmainE*ml
Q8elati e;ayout xmlns"androidJ2http344schemas.android.com4ap 4res4android2 xmlns"toolsJ2http344schemas.android.com4tools2 android"layoutRwidthJ2match)parent2 android"layoutRheightJ2match)parent2 S Q$extIiew android"layoutRwidthJ2wrap)content2 android"layoutRheightJ2wrap)content2 #S QSwitch android"idJ256id4switchbutton2 android"layoutRwidthJ2wrap)content2 android"layoutRheightJ2wrap)content2 android"text-nJ2"urn *n2 android"text-ffJ2"urn *!!2 android"on(lickJ2on"oggleClic ed2 #S Q#8elati e;ayoutS

!00

3G -pen the :ainActi ity..a a


2G Add the lines >import android.widget.(ompound0uttonA< >import

android.widget.SwitchA

6G

Get references to the Switch button created in activit JmainE*ml

Switch switchbtn J *Switch, findIiew0y)d*8.id.switchbutton,&

/G Attach ;istener to the switchbtn Switch< to do this< call

set-n(hecked(hange;istener method

switchbtn.set-n(hecked(hange;istener*,

5G 8espond to click using the method onChec1e(Change( *(ompound0utton

buttonIiew< boolean is(hecked,

7G Show a toast displaying the toggle state

4isting 03?
!ac1age com.AP0ook.switcbutton& im!ort im!ort im!ort im!ort im!ort im!ort android.os.0undle& android.app.Acti ity& android. iew.Iiew& android.widget.(ompound0utton& android.widget.Switch& android.widget.$oast&

!00

!ublic class :ainActi ity e*ten(s Acti ityK +- erride !ublic voi( on(reate*0undle sa ed)nstanceState, K su!er.on(reate*sa ed)nstanceState,& set(ontentIiew*8.layout.activity)main,& Switch switchbtn J *Switch, findIiew0y)d*8.id.switchbutton,& switchbtn.set-n(hecked(hange;istener*ne& (ompound0utton.-n(hecked(hange;istener*, K +- erride !ublic voi( on(hecked(hanged*(ompound0utton buttonIiew< boolean is(hecked, K if *is(hecked, K ## $he toggle is enabled $oast toast J $oast.ma e"e#t*:ainActi ity.this< U-4U< $oast.$%&'"()$*&',& toast.show*,& L else K ## $he toggle is disabled $oast toast J $oast.ma e"e#t*:ainActi ity.this< U-11U< $oast.$%&'"()$*&',& toast.show*,& L L L,& L L

!00

)!inners
Spinners pro ide a Duick way to select one alue from a set. )n the default state< a spinner shows its currently selected alue. $ouching the spinner displays a dropdown menu with all other a ailable alues< from which the user can select a new one.

$o populate the spinner with a list of choices< you then need to specify a SpinnerAdapter in your Acti ity

!G (reate a new pro.ect and name it )!inner -*am!le 2G (reate the xml layout *see Android -. design with /0$ on Ama1on)

!00

Activit JmainE*ml
Q;inear;ayout xmlns"androidJ2http344schemas.android.com4ap 4res4android2 xmlns"toolsJ2http344schemas.android.com4tools2 android"layoutRwidthJ2match)parent2 android"layoutRheightJ2match)parent2 android"orientationJ2vertical2 S Q;inear;ayout android"layoutRmargin$opJ228sp2 android"orientationJ2hori1ontal2 android"layoutRwidthJ2!ill)parent2 android"layoutRheightJ2wrap)content2 S Q$extIiew android"textJ25string4te#t12 android"idJ256id4"e#t7iew9tring2 android"layoutRwidthJ2!ill)parent2 android"layoutRheightJ2wrap)content2S Q#$extIiewS Q#;inear;ayoutS Q;inear;ayout android"layoutRmargin$opJ228sp2 android"orientationJ2hori1ontal2 android"layoutRwidthJ2!ill)parent2 android"layoutRheightJ2wrap)content2 S Q$extIiew android"textJ25string4!rom2 android"idJ256id4"e#t7iew,rom2 android"layoutRwidthJ2wrap)content2 android"layoutRheightJ2wrap)content2 S Q#$extIiewS QSpinner android"idJ256id4spinner12 android"entriesJ25array4spinner1)temperature2 android"layoutRwidthJ2200dp2 android"layoutRheightJ2wrap)content2S Q#SpinnerS Q#;inear;ayoutS Q;inear;ayout android"orientationJ2vertical2 android"layoutRwidthJ2!ill)parent2 android"layoutRheightJ2wrap)content2 android"gra ityJ2center2 android"layoutRmargin$opJ212sp2 S Q0utton android"textJ25string4convert2 android"idJ256id4=utton012 android"layoutRwidthJ2!ill)parent2 android"layoutRheightJ2wrap)content2 android"layoutRmargin$opJ212sp2S Q#0uttonS Q#;inear;ayoutS Q#;inear;ayoutS

!00

)tringsE*ml
QresourcesS Qstring nameJ2app)name2SSpinner BxampleQ#stringS Qstring nameJ2hello)world2S9ello world[Q#stringS Qstring nameJ2menu)settings2SSettingsQ#stringS Qstring nameJ2title)activity)main2S:ainActi ityQ#stringS Qstring nameJ2te#t12SSelect temperatureQ#stringS Qstring nameJ2convert2S(on ertQ#stringS Qstring nameJ2result2S8esultQ#stringS Qstring nameJ2to2S$oQ#stringS Qstring nameJ2!rom2S$emperatureQ#stringS QstringGarray nameJ2spinner1)temperature2S QitemS1ahrenheitQ#itemS QitemS(elsiusQ#itemS QitemSFel inQ#itemS Q#stringGarrayS Q#resourcesS

3G -pen the :ainActi ity..a a 2G Add the lines import import import import android.widget.AdapterIiew& android.widget.AdapterIiew.-n)temSelected;istener& android.widget.ArrayAdapter& android.widget.Spinner&

6G Get reference to the spinner created in acti ityRmain.xml

final Spinner spinner J *Spinner, findIiew0y)d*8.id.spinner1,& /G (reate an ArrayAdapter

!00

Table L and Table "; gi e the list of methods associated to thess classes

5G Specify the drop down Iiew resource setDro!Do&nVie&%esourceBint# method

7G Set the Adapter for the Spinner


XG $o #roceed 0o% need to call the method setA(a!terB#

spinner.setAdapter*adapter,&
!0G Specify the interface implementation by calling setOnItem)electe(4istenerB#

spinner.set-n)temSelected;istener*ne& -n)temSelected;istener*, *see anonymous class in chapter1)


!!G 8espond to user selections

'hen the user selects an item from the dropGdown< the Spinner ob.ect recei es an onGitemGselected e ent.

!00

$o define the selection e ent handler for a spinner< implement the Ada1ter2iew.(n3tem&elected,istener interface and the corresponding on3tem&elected"# callback method *see $able 3 on3tem&elected"# method,
!ublic voi( on)temSelected*AdapterIiewQ_S parent< Iiew iew< int pos< long id, K ## An item was selected. %ou can retrie e the selected item using ## parent.get)temAtPosition*pos, L +- erride !ublic voi( on4othingSelected*AdapterIiewQ_S parent, K ## Another interface callback L

!2G 'hen a user selects an item< a toast will return the selected item.

$oast.ma e"e#t*parent.get(ontext*,<U%ou select U V parent.get)temAtPosition*pos,.toString*,< $oast.$%&'"()$*&',.show*,&

4isting 03L
!ac1age com.AP0ook.spinnerexample& im!ort im!ort im!ort im!ort im!ort im!ort im!ort im!ort android.app.Acti ity& android.os.0undle& android. iew.Iiew& android.widget.AdapterIiew& android.widget.AdapterIiew.-n)temSelected;istener& android.widget.ArrayAdapter& android.widget.Spinner& android.widget.$oast&

!ublic class :ainActi ity e*ten(s Acti ity K +- erride !ublic voi( on(reate*0undle sa ed)nstanceState, K su!er.on(reate*sa ed)nstanceState,& set(ontentIiew*8.layout.activity)main,& final Spinner spinner J *Spinner, findIiew0y)d*8.id.spinner1,& ArrayAdapterQ(harSeDuenceS adapter J ArrayAdapter.create,romResource*this< 8.array.spinner1)temperature< android.8.layout.simple)spinner)item,& adapter.setEropEownIiew8esource*android.8.layout.simple)spinner)dropdown)item,& ## Apply the adapter to the spinner spinner.setAdapter*adapter,& spinner.set-n)temSelected;istener*ne& -n)temSelected;istener*, K

!00

+- erride !ublic voi( on)temSelected*AdapterIiewQ_S parent< Iiew iew< int pos< long id, K $oast.ma e"e#t*parent.get(ontext*,<U%ou select U V parent.get)temAtPosition*pos,.toString*,< $oast.$%&'"()$*&',.show*,& L +- erride !ublic voi( on4othingSelected*AdapterIiewQ_S parent, K ## Another interface callback L L L L,&

%esult shoul( loo1 li1e this:

-*ercise
)mplement a simple +em1erature 4on erter application.

Design $he design consists of"

!00

2 Bdit$ext< the first one to recei e the user input and the second one to show the con ersion result. 2 buttons *$o (elsius and $o 1ahrenheit,

8ormula 1ormulas needed to con ert temperature to and from both (elsius and 1ahrenheit C J *6#X,`*1G32, 8 J *X#6,`(V32 1J1ahrenheit (J(elsius

8unctionalit " $he user enter the temperature to con ert 'hen the user click ] $o (elsius ^ or ] $o 1ahrenheit ^ button the calculation result is showing in the Bdit$ext %esult< with the set$ext*, method.

)olution: Iisit http"##keroob.com#index.php#andro for the solution< there are many possible solutions< you can exchange your android pro.ect in Cip format with other users on the website.

#ppendi1 #: Compilation error

!00

Cause" o erride annotation )n .a a / the o erride annotation no longer applies to interface methods this can cause errors in your application when the compiler are set to .dk !./ in android< here is how to proceed
!, (lick Project S Pro!erties

2, )n the Properties window choose Java Com!iler and click M -nable !roject

s!ecific settings N to select the JEF ersion to use.

!00

3, (lick A!!l then O>

)f you wish to set your .dk ersion as the default< click F Configure &or1s!ace )ettingsC F at the top right corner of the Properties windows then click A!!l < O>E

!00

Das könnte Ihnen auch gefallen