Upload
hoang-ngoc-hung
View
228
Download
0
Embed Size (px)
Citation preview
8/12/2019 Android 3 7 CC
1/747
8/12/2019 Android 3 7 CC
2/747
8/12/2019 Android 3 7 CC
3/747
The Busy Coder's Guide to Android Developmentby Mark L. Murphy
Copyright 2008-2011 CommonsWare, LLC. All ights eser!e".#rinte" in the $nite" %tates o& Ameri'a.
CommonsWare books may be pur'hase" in printe" (bulk) or "igital &orm &or e"u'ational orbusiness use. *or more in&ormation, 'onta't [email protected] .
#rinting +istoryo! 2011 ersion /. % 3 8-0-3814 80-0-3
5he CommonsWare name an" logo, 6 usy Co"er7s ui"e9, an" relate" tra"e "ress aretra"emarks o& CommonsWare, LLC.
All other tra"emarks re&eren'e" in this book are tra"emarks o& their respe'ti!e &irms.
5he publisher an" author(s) assume no responsibility &or errors or omissions or &or "amagesresulting &rom the use o& the in&ormation 'ontaine" herein.
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
4/747
Table of Contents
Welcome to the Warescription!........................................................xxiii
Preface.................................................................................................xxv
Wel'ome to the ook: ..............................................................................;;! Wares'ription ............................................................................................;;!
etting +elp .............................................................................................;;!i
ook ug ounty ....................................................................................;;!ii
%our'e Co"e An" ts Li'ense ................................................................;;!iii
Creati!e Commons an" the *our-to-*ree (
8/12/2019 Android 3 7 CC
5/747
#% ..........................................................................................................
#hone %er!i'es ........................................................................................4
5he ig #i'ture...>& 5his ook ....................................................................4
"o# To Get $tarted.................................................................................%
+ar"=are eBuirements .............................................................................. a!a .................................................................................................................8
nstall the @D ........................................................................................8
Learn a!a ...............................................................................................3
nstall the An"roi" %@D ...............................................................................3
nstall the ase 5ools ............................................................................10
nstall the %@Ds an" A""->ns .............................................................10
nstall the A@5 &or E'lipse ..........................................................................11
nstall Apa'he Ant .......................................................................................1/
%et $p the Emulator ....................................................................................1ut >& t ......................................................................
8/12/2019 Android 3 7 CC
7/747
1sin 2345Based 4ayouts....................................................................06
What s an FML- ase" LayoutI ................................................................43
Why $se FML- ase" LayoutsI ................................................................. 0
>D, %o What @oes t Look LikeI ............................................................... 1
What7s With the J %ignsI .......................................................................... 2 An" We Atta'h 5hese to the a!a...+o=I ................................................. 2
5he est o& the %tory .................................................................................. /
+mployin Basic Wid ets......................................................................%%
Assigning Labels .........................................................................................
utton, utton, Who7s ot the uttonI ................................................... 8
*leeting mages ........................................................................................... 3
*iel"s o& reen. >r >ther Colors. ..............................................................81
ust Another o; to Che'k .........................................................................8/
@on7t Like Che'kbo;esI +o= About 5ogglesI ........................................84
5urn the a"io $p ......................................................................................8
t7s Kuite a ie= .........................................................................................30
#a""ing .................................................................................................30
>ther $se&ul #roperties ......................................................................30
$se&ul Metho"s .....................................................................................31
Colors.....................................................................................................31
Wor7in #ith Containers......................................................................6,
5hinking Linearly .......................................................................................3ur %tory ............................................................142
etter. %tronger. *aster. ............................................................................14/
$sing 'on!ert ie= ..............................................................................14/
$sing the +ol"er #attern ...................................................................14ntera'ti!e o=s ........................................................................................14
$till 3ore Wid ets and Containers..................................................... %*
#i'k an" Choose ........................................................................................1
5ime Deeps *lo=ing Like a i!er .............................................................180
%eeking esolution ....................................................................................182
#utting t >n My 5ab ................................................................................18/
5he #ie'es ............................................................................................18&& .....................................................................................13ptions (>h, My:) ........................................21ptions ......................................................................................218
Menus in Conte;t .....................................................................................220
viii
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
10/747
5aking a #eek .............................................................................................221
?et More n&lation ....................................................................................224
Menu FML %tru'ture .........................................................................22
Menu >ptions an" FML ....................................................................228
n&lating the Menu .............................................................................223n the Lan" o& Menus an" +oney ............................................................2/1
$ho#in Pop51p 3essa es..................................................................),,
aising 5oasts ............................................................................................2//
Alert: Alert: ................................................................................................2/h Where +as My $ 5hrea" oneI ........................................2 /
Asyn'ing *eeling .......................................................................................2 /
5he 5heory ..........................................................................................2 /
Asyn'5ask, eneri's, an" arargs ....................................................2 ther ame... .......................................//
xi
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
13/747
"andlin 3ultiple $creen $i
8/12/2019 Android 3 7 CC
14/747
5he +olographi' 5heme ........................................................................../
%tan"ar" 5hemes !ersus @e&ault 5hemes ......................................../ 4
@ealing =ith the est o& the @e!i'es ....................................................../
1sin the Action Bar............................................................................,%6
Enabling the A'tion ar .........................................................................../ 3#romoting Menu tems to the A'tion ar ............................................../80
espon"ing to the Logo ............................................................................/81
A""ing Custom ie=s to the A'tion ar ................................................/82
@e&ining the Layout.........................................................................../8/
#utting the Layout in the NMenuN ...................................................../8perations !ia Apa'he +ttpClient ......................................... 01
#arsing esponses .............................................................................. 0/
%tu&& 5o Consi"er................................................................................ 0
An"roi"+ttpClient ............................................................................. 04Le!eraging nternet-A=are An"roi" Components ................................ 0
@o=nloa"ing *iles .............................................................................. 0
Continuing >ur Es'ape *rom anky Co"e .............................................. 13
Making etro A# s *eel e= Again ......................................................... 13
$ervices> The Theory............................................................................*),
Why %er!i'esI ............................................................................................ 2/
%etting $p a %er!i'e .................................................................................. 2bHe'ts ................................................................. /0
roa"'ast ntents ................................................................................ /0
#en"ing esults ................................................................................... /1
Messenger ............................................................................................ /1
oti&i'ations ........................................................................................ /2
Basic $ervice Patterns..........................................................................*,,
5he @o=nloa"er ........................................................................................ //
5he @esign .......................................................................................... /n ................................................................................................... 30
5he Dey 5o t All ....................................................................................... 30
5he are ones ......................................................................................... 32
>ptional Maps .................................................................................... 3pen +an"set Allian'e.
An", most o& all, thanks &or your interest in this book: sin'erely hope you&in" it use&ul an" at least o''asionally entertaining.
Warescription
5his book =ill be publishe" both in print an" in "igital (ebook) &orm. 5he
ebook !ersions o& all CommonsWare titles are a!ailable !ia an annualsubs'ription S the Wares'ription.
5he Wares'ription entitles you, &or the "uration o& your subs'ription, toebook &orms o&all CommonsWare titles, not Hust the one you are rea"ing.
xxv
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
27/747
#resently, CommonsWare o&&ers #@* an" Din"leT other ebook &ormats =illbe a""e" base" on interest an" the openness o& the &ormat.
Ea'h subs'riber gets personali e" e"itions o& all e"itions o& ea'h title boththose mirroring printe" e"itions an" in-bet=een up"ates that are onlya!ailable in ebook &orm. 5hat =ay, your ebooks are ne!er out o& "ate &orlong, an" you 'an take a"!antage o& ne= material as it is ma"e a!ailableinstea" o& ha!ing to =ait &or a =hole ne= print e"ition. *or e;ample, =henne= releases o& the An"roi" %@D are ma"e a!ailable, this book =ill beBui'kly up"ate" to be a''urate =ith 'hanges in the A# s.
*rom time to time, subs'ribers =ill also re'ei!e a''ess to subs'riber-onlyonline material, both short arti'les an" not-yet-publishe" ne= titles.
Also, i& you o=n a print 'opy o& a CommonsWare book, an" it is in goo"'lean 'on"ition =ith no marks or sti'kers, you 'an e;'hange that 'opy &or a"is'ount o&& the Wares'ription pri'e.
& you are intereste" in a Wares'ription, !isit the Wares'ription se'tion o&the CommonsWare Web site .
?ou 'an &in" out =hen ne= releases o& this book are a!ailable !ia
5he 'ommonsguy 5=itter &ee" 5he Commons log 5he Wares'ription ne=sletter, =hi'h you 'an subs'ribe to o&& o&
your Wares'ription page
Getting Help
& you ha!e Buestions about the book e;amples, !isit %ta'k>!er&lo= an" aska Buestion, tagge" =ith android an" commons#are .
& you ha!e general An"roi" "e!eloper Buestions, !isit %ta'k>!er&lo= an"ask a Buestion, tagge" =ith android (an" any other rele!ant tags, su'h as (ava ).
xxvi
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
http://commonsware.com/warescription.htmlhttp://commonsware.com/warescription.htmlhttp://twitter.com/commonsguyhttp://twitter.com/commonsguyhttp://commonsware.com/bloghttp://wares.commonsware.com/http://wares.commonsware.com/http://stackoverflow.com/http://stackoverflow.com/http://commonsware.com/warescription.htmlhttp://twitter.com/commonsguyhttp://commonsware.com/bloghttp://wares.commonsware.com/http://stackoverflow.com/8/12/2019 Android 3 7 CC
28/747
Book Bug Bounty
*in" a problem in one o& our booksI Let us kno=:
e the &irst to report a uniBue 'on'rete problem in the 'urrent "igitale"ition, an" =e7ll gi!e you a 'oupon &or a si;-month Wares'ription as abounty &or helping us "eli!er a better pro"u't. ?ou 'an use that 'oupon toget a ne= Wares'ription, rene= an e;isting Wares'ription, or gi!e the'oupon to a &rien", 'olleague, or some ran"om person you meet on thesub=ay.
y N'on'reteN problem, =e mean things like
5ypographi'al errors %ample appli'ations that "o not =ork as a"!ertise", in the
en!ironment "es'ribe" in the book *a'tual errors that 'annot be open to interpretation
y NuniBueN, =e mean ones not yet reporte". Ea'h book has an errata pageon the CommonsWare Web siteT most kno=n problems =ill be liste" there.>ne 'oupon is gi!en per email 'ontaining !ali" bug reports.
We appre'iate hearing about Nso&terN issues as =ell, su'h as
#la'es =here you think =e are in error, but =here =e &eel ourinterpretation is reasonable
#la'es =here you think =e 'oul" a"" sample appli'ations, ore;pan" upon the e;isting material
%amples that "o not =ork "ue to Nshi&ting san"sN o& the un"erlyingen!ironment (e.g., 'hange" A# s =ith ne= releases o& an %@D)
+o=e!er, those Nso&terN issues "o not Buali&y &or the &ormal bountyprogram.
e sure to 'he'k the book7s errata page , though, to see i& your issue hasalrea"y been reporte".
xxvii
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
http://commonsware.com/Android/erratahttp://commonsware.com/Android/errata8/12/2019 Android 3 7 CC
29/747
Kuestions about the bug bounty, or problems you =ish to report &or bounty'onsi"eration, shoul" be sent to bountyJ'ommons=are.'om .
Source Co e n "ts #icense
5he sour'e 'o"e samples sho=n in this book are a!ailable &or "o=nloa"&rom thebook7s it+ub repository . All o& the An"roi" proHe'ts are li'ense"un"er the Apa'he 2.0 Li'ense , in 'ase you ha!e the "esire to reuse any o& it.
& you =ish to use the sour'e 'o"e &rom the CommonsWare Web site, bearin min" a &e= things
1. 5he proHe'ts are set up to be built by Ant, not by E'lipse. & you =ishto use the 'o"e =ith E'lipse, you =ill nee" to 'reate a suitable An"roi" E'lipse proHe't an" import the 'o"e an" other assets.
2. ?ou shoul" "elete buil".;ml, then run android update project-p ... (=here ... is the path to a proHe't o& interest) on thoseproHe'ts you =ish to use, so the buil" &iles are up"ate" &or your An"roi" %@D !ersion.
Creative Commons an the $our%to%$ree&'($) Guarantee
Ea'h CommonsWare book e"ition =ill be a!ailable &or use un"er theCreati!e Commons Attribution- on'ommer'ial-%hareAlike /.0 li'ense as o&the &ourth anni!ersary o& its publi'ation "ate, or =hen
8/12/2019 Android 3 7 CC
30/747
*or more "etails on the Creati!e Commons Attribution- on'ommer'ial-%hareAlike /.0 li'ense, !isit the Creati!e Commons Web site.
ote that &uture e"itions o& this book =ill be'ome &ree on later "ates, ea'h&our years &rom the publi'ation o& that e"ition or base" on sales o& thatspe'i&i' e"ition. eleasing one e"ition un"er the Creati!e Commons li'ense"oes not automati'ally release all e"itions un"er that li'ense.
ckno*le gments
=oul" like to thank the An"roi" team, not only &or putting out a goo"pro"u't, but &or in!aluable assistan'e on the An"roi" oogle roups.
%ome o& the i'ons use" in the sample 'o"e =ere pro!i"e" by the u!ola
i'on set.
xxix
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
http://www.icon-king.com/?p=15http://www.icon-king.com/?p=158/12/2019 Android 3 7 CC
31/747
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
32/747
PART I Core Concepts
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
33/747
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
34/747
CHAPTER 1
The Big Picture
An"roi" is e!ery=here. #hones. 5ablets. 5 s an" set-top bo;es po=ere" byoogle 5 . %oon, An"roi" =ill be in 'ars an" all sort o& other pla'es as =ell.
+o=e!er, the general theme o& An"roi" "e!i'es =ill be smaller s'reensan"Qor no har"=are keyboar". An", by the numbers, An"roi" =ill probablybe most asso'iate" =ith smartphones &or the &oreseeable &uture.
*or "e!elopers, this has bene&its an" "ra=ba'ks.
>n the plus si"e, An"roi"-style smartphones are se;y. >&&ering nternetser!i'es o!er mobile "e!i'es "ates ba'k to the mi"-13307s an" the +an"hel"@e!i'e Markup Language (+@ML). +o=e!er, only in re'ent years ha!ephones 'apable o& nternet a''ess taken o&&. o=, thanks to tren"s like te;tmessaging an" to pro"u'ts like Apple7s i#hone, phones that 'an ser!e asnternet a''ess "e!i'es are rapi"ly gaining popularity. %o, =orking on
An"roi" appli'ations gi!es you e;perien'e =ith an interesting te'hnology(An"roi") in a &ast-mo!ing market segment ( nternet-enable" phones), =hi'h is al=ays a goo" thing.
5he problem 'omes =hen you a'tually ha!e to program the "arn things.
Anyone =ith e;perien'e in programming &or #@As or phones has &elt thepain o& phones simply being small in all sorts o& "imensions
+
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
35/747
8/12/2019 Android 3 7 CC
36/747
The Big Picture
?ou get a &airly rigi" an" un'ommon &rame=ork in =hi'h yourprograms nee" to run so they 'an be Ngoo" 'iti ensN on the phonean" not inter&ere =ith other programs or the operation o& the phoneitsel&
As you might e;pe't, mu'h o& this book "eals =ith that &rame=ork an" ho= you =rite programs that =ork =ithin its 'on&ines an" take a"!antage o& its'apabilities.
What n roi s re ,a e -f
When you =rite a "esktop appli'ation, you are Nmaster o& your o=n
"omainN. ?ou laun'h your main =in"o= an" any 'hil" =in"o=s S like"ialog bo;es S that are nee"e". *rom your stan"point, you are your o=n =orl", le!eraging &eatures supporte" by the operating system, but largelyignorant o& any other program that may be running on the 'omputer at thesame time. & you "o intera't =ith other programs, it is typi'ally through an A# , su'h as using @ C (or &rame=orks atop it) to 'ommuni'ate =ithMy%KL or another "atabase.
An"roi" has similar 'on'epts, but pa'kage" "i&&erently, an" stru'ture" tomake phones more 'rash-resistant.
Activities
5he buil"ing blo'k o& the user inter&a'e is the activity . ?ou 'an think o& ana'ti!ity as being the An"roi" analogue &or the =in"o= or "ialog in a"esktop appli'ation, or the page in a 'lassi' Web app. An"roi" is "esigne"to support lots o& 'heap a'ti!ities, so you 'an allo= users to keep 'li'king tobring up ne= a'ti!ities an" tapping the ACD button to ba'k up, Hust like
they "o in a Web bro=ser.
.
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
37/747
The Big Picture
Services
A'ti!ities are short-li!e" an" 'an be shut "o=n at any time. %er!i'es, on theother han", are "esigne" to keep running, i& nee"e", in"epen"ent o& anya'ti!ity. ?ou might use a ser!i'e &or 'he'king &or up"ates to an %% &ee", orto play ba'k musi' e!en i& the 'ontrolling a'ti!ity is no longer operating. ?ou =ill also use ser!i'es &or s'he"ule" tasks (N'ron HobsN) an" &or e;posing'ustom A# s to other appli'ations on the "e!i'e, though those are relati!elya"!an'e" 'apabilities.
Content Providers
Content pro!i"ers pro!i"e a le!el o& abstra'tion &or any "ata store" on the"e!i'e that is a''essible by multiple appli'ations. 5he An"roi""e!elopment mo"el en'ourages you to make your o=n "ata a!ailable toother appli'ations, as =ell as your o=n S buil"ing a 'ontent pro!i"er lets you "o that, =hile maintaining 'omplete 'ontrol o!er ho= your "ata getsa''esse".
Intents
ntents are system messages, running aroun" the insi"e o& the "e!i'e,noti&ying appli'ations o& !arious e!ents, &rom har"=are state 'hanges (e.g.,an %@ 'ar" =as inserte"), to in'oming "ata (e.g., an %M% message arri!e"),to appli'ation e!ents (e.g., your a'ti!ity =as laun'he" &rom the "e!i'e7smain menu). ot only 'an you respon" to an Intent , but you 'an 'reate your o=n, to laun'h other a'ti!ities, or to let you kno= =hen spe'i&i'situations arise (e.g., raise su'h-an"-so Intent =hen the user gets =ithin 100meters o& this-an"-su'h lo'ation).
'
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
38/747
The Big Picture
Stuff t /our 0isposal
Stor !e
?ou 'an pa'kage "ata &iles =ith your appli'ation, &or things that "o not'hange, su'h as i'ons or help &iles. ?ou also 'an 'ar!e out a small bit o&spa'e on the "e!i'e itsel&, &or "atabases or &iles 'ontaining user-entere" orretrie!e" "ata nee"e" by your appli'ation. An", i& the user supplies bulkstorage, like an %@ 'ar", you 'an rea" an" =rite &iles on there as nee"e".
"et#or$
An"roi" "e!i'es =ill generally be nternet-rea"y, through one'ommuni'ations me"ium or another. ?ou 'an take a"!antage o& thenternet a''ess at any le!el you =ish, &rom ra= a!a so'kets all the =ay upto a built-in WebDit-base" Web bro=ser =i"get you 'an embe" in yourappli'ation.
%ultimedi
An"roi" "e!i'es ha!e the ability to play ba'k an" re'or" au"io an" !i"eo. While the spe'i&i's may !ary &rom "e!i'e to "e!i'e, you 'an Buery the"e!i'e to learn its 'apabilities an" then take a"!antage o& the multime"ia'apabilities as you see &it, =hether that is to play ba'k musi', take pi'tures =ith the 'amera, or use the mi'rophone &or au"io note-taking.
GPS
An"roi" "e!i'es =ill &reBuently ha!e a''ess to lo'ation pro!i"ers, su'h as#%, that 'an tell your appli'ations =here the "e!i'e is on the &a'e o& theEarth. n turn, you 'an "isplay maps or other=ise take a"!antage o& thelo'ation "ata, su'h as tra'king a "e!i'e7s mo!ements i& the "e!i'e has beenstolen.
1
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
39/747
The Big Picture
Phone Services
An", o& 'ourse, An"roi" "e!i'es are typi'ally phones, allo=ing yourso&t=are to initiate 'alls, sen" an" re'ei!e %M% messages, an" e!erythingelse you e;pe't &rom a mo"ern bit o& telephony te'hnology.
The Big Picture222-f This Book
+ere is =hat7s 'oming in the rest o& this book
5he ne;t t=o 'hapters are "esigne" to get you going Bui'kly =ith the An"roi" en!ironment, through a series o& step-by-step, tutorial-style
instru'tions &or setting up the tools you nee", 'reating your &irst proHe't,an" getting that &irst proHe't running on the An"roi" emulator.
5he three 'hapters that &ollo= try to e;plain a bit more about =hat Husthappene" in those &irst t=o 'hapters. We e;amine the An"roi" proHe't that =e 'reate", talk a bit more about E'lipse , an" "is'uss some things =e 'oul"a"" to the proHe't to help it run on more "e!i'es an" su'h.
5he bulk o& the book is e;ploring !arious 'apabilities o& the An"roi" A# s Sho= to 'reate 'omponents like a'ti!ities, ho= to a''ess the nternet an"lo'al "atabases, ho= to get your lo'ation an" sho= it on a map, an" so&orth.
3
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
40/747
CHAPTER &
Ho* To Get Starte
Let us get you set up =ith the pie'es an" parts ne'essary to buil" an An"roi" app.
@ T+ the instru'tions presente" here are a''urate as o& the time o& this =riting. +o=e!er, the tools 'hange rapi"ly, an" so these instru'tions maybe out o& "ate by the time you rea" this. #lease re&er to the An"roi" @e!elopers Web site &or 'urrent instru'tions, using this as a base gui"elineo& =hat to e;pe't.
Har *are 4e5uirementsCompiling an" buil"ing an An"roi" appli'ation, on its o=n, is notespe'ially har"=are-intensi!e, e;'ept &or !ery large proHe'ts. +o=e!er,there are t=o 'ommonly-use" tools that "eman" more &rom your"e!elopment ma'hine E'lipse an" the An"roi" emulator. >& the t=o, theemulator poses the bigger problem.
5he more AM you ha!e, the better. / or higher is a !ery goo" i"ea i&
you inten" to use E'lipse an" the emulator together.
A &aster C#$ is also a goo" i"ea. +o=e!er, the An"roi" emulator onlyutili es a single 'ore &rom your "e!elopment ma'hine. +en'e, it is thesingle-'ore spee" that matters. 5he best C#$ to use is one that 'an le!eragemultiple 'ores to gi!e =hat amounts to a &aster single 'ore, su'h as ntel7s
6
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
http://developer.android.com/http://developer.android.com/http://developer.android.com/http://developer.android.com/8/12/2019 Android 3 7 CC
41/747
Ho* To Get Starte
Core i =ith 5urbo oost. *or a emulator simulating a larger-s'reene""e!i'e (e.g., tablet, tele!ision), a Core i that 'an NboostN up to /.< +makes "e!elopment mu'h more pleasant. Con!ersely, a C#$ like a Core 2@uo =ith a 2. + 'lo'k spee" results in a tablet emulator that is nearly
unusable. %maller s'reens (e.g., phones) 'an run a''eptably on 2. + an"(slightly) slo=er C#$s.
7ava
When you =rite An"roi" appli'ations, you typi'ally =rite them in a!asour'e 'o"e. 5hat a!a sour'e 'o"e is then turne" into the stu&& that An"roi" a'tually runs (@al!ik byte'o"e in an A#D &ile).
+en'e, the &irst thing you nee" to "o is get set up =ith a a!a "e!elopmenten!ironment an" be rea"y to start =riting a!a 'lasses.
Inst ll the D(
?ou nee" to obtain an" install the o&&i'ial %unQ>ra'le a!a %E %@D ( @D). ?ou 'an obtain this &rom the >ra'le a!a Web site &or Win"o=s an" Linu;,an" presumably &rom Apple &or >% F. 5he plain @D (sans any Nbun"lesN)shoul" su&&i'e. *ollo= the instru'tions supplie" by >ra'le or Apple &orinstalling it on your ma'hine. At the time o& this =riting, An"roi" supports a!a an" a!a 4. ote that An"roi" "oes not support a!a .
Alternative Java Compilers
n prin'iple, you are suppose" to use the o&&i'ial %unQ>ra'le a!a %E %@D.n pra'ti'e, it appears that >pen @D also =orks, at least on $buntu.
+o=e!er, the &urther remo!e" you get &rom the o&&i'ial %unQ>ra'leimplementation, the less likely it is that it =ill =ork. *or e;ample, the $Compiler &or a!a ( C ) may not =ork =ith An"roi".
8
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
http://www.oracle.com/technetwork/java/index.htmlhttp://www.oracle.com/technetwork/java/index.htmlhttp://www.oracle.com/technetwork/java/index.html8/12/2019 Android 3 7 CC
42/747
Ho* To Get Starte
)e rn v
5his book, like most books an" "o'umentation on An"roi", assumes that you ha!e basi' a!a programming e;perien'e. & you la'k this, you reallyshoul" 'onsi"er spen"ing a bit o& time on a!a &un"amentals, be&ore you"i!e into An"roi". >ther=ise, you may &in" the e;perien'e to be&rustrating.
& you are in nee" o& a 'rash 'ourse in a!a to get in!ol!e" in An"roi""e!elopment, here are the 'on'epts you nee" to su''ee", presente" in noparti'ular or"er
Language &un"amentals (&lo= 'ontrol, et'.) Classes an" obHe'ts Metho"s an" "ata members #ubli', pri!ate, an" prote'te" %tati' an" instan'e s'ope E;'eptions 5hrea"s an" 'on'urren'y 'ontrol Colle'tions eneri's *ile Q> e&le'tion nter&a'es
"nstall the n roi S09
5he An"roi" %@D gi!es you all the tools you nee" to 'reate an" test An"roi" appli'ations. t 'omes in t=o parts the base tools, plus !ersion-spe'i&i' %@Ds an" relate" a""-ons.
:
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
43/747
Ho* To Get Starte
Inst ll the B se Tools
5he An"roi" "e!eloper tools 'an be &oun" on the An"roi" @e!elopers Web site . @o=nloa" the R # or 5 R &ile appropriate &or your plat&orm an" unR #it in some likely spot S there is no spe'i&i' path that is reBuire". Win"o=susers also ha!e the option o& running a sel&-installing EFE &ile.
Inst ll the SD(s nd Add*+ns
nsi"e the tools/ "ire'tory o& your An"roi" %@D installation &rom thepre!ious step, you =ill see an android bat'h &ile or shell s'ript. & you runthat, you =ill be presente" =ith the An"roi" %@D Manager.
At this point, =hile you ha!e some o& the buil" tools, you la'k the a!a &ilesne'essary to 'ompile an An"roi" appli'ation. ?ou also la'k a &e= a""itionalbuil" tools, plus the &iles ne'essary to run an An"roi" emulator. 5he'he'kbo;es in"i'ate =hi'h pa'kages you =ant to install S by "e&ault, it pre-'he'ks a number o& them.
?ou =ill =ant to 'he'k the &ollo=ing items
N%@D #lat&ormN &or all An"roi" %@D releases you =ant to testagainst S &or this book A# 8 (An"roi" 2.2) is re'ommen"e"
N@o'umentation &or An"roi" %@DN an" NA M EA ! a %ystemmageN&or the latest An"roi" %@D release
N%amples &or %@DN &or the latest An"roi" %@D release, an" perhaps&or ol"er releases i& you =ish
N oogle A# s by oogle n'.N&or ea'h An"roi" %@D release &or =hi'h you are "o=nloa"ing the plat&orm (see &irst bullet)
An"roi" %@D #lat&orm-tools An"roi" %upport pa'kage (in the E;tras group at the bottom o& the
tree)
5hen, 'li'k the nstall button beneath the tree on the right, =hi'h bringsup a li'ense 'on&irmation "ialog
+;
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
http://developer.android.com/sdk/index.htmlhttp://developer.android.com/sdk/index.htmlhttp://developer.android.com/sdk/index.htmlhttp://developer.android.com/sdk/index.html8/12/2019 Android 3 7 CC
44/747
Ho* To Get Starte
$igure +2 n roi S09 ,anger "nstalling Packages
e!ie= an" a''ept the li'enses, then 'li'k the nstall button. At this point,this is a &ine time to go get lun'h. >r, perhaps "inner. $nless you ha!e asubstantial nternet 'onne'tion, "o=nloa"ing all o& this "ata an"unpa'king it =ill take a &air bit o& time.
When the "o=nloa" is 'omplete, you 'an 'lose up the %@D Manager i& you =ish, though =e =ill use it to set up the emulator in a later step o& this 'hapter .
"nstall the 0T for
8/12/2019 Android 3 7 CC
45/747
8/12/2019 Android 3 7 CC
46/747
Ho* To Get Starte
$igure .2
8/12/2019 Android 3 7 CC
47/747
Ho* To Get Starte
& you "o not ha!e Ant, you 'an obtain it &rom the Apa'he Ant Web site . 5hey ha!e &ull installation instru'tions in the Ant manual, but the basi'steps are
1. $npa'k the R # ar'hi!e =here!er it may make sense on yourma'hine
2. A"" a JAVA !"#$ en!ironment !ariable, pointing to =here your @Dis installe", i& you "o not ha!e one alrea"y
/. A"" an A%& !"#$ en!ironment !ariable, pointing to the "ire'tory =here you unpa'ke" Ant in the &irst step abo!e
8/12/2019 Android 3 7 CC
48/747
Ho* To Get Starte
$igure '2 >0 ,anager
Cli'k the e=... button to 'reate a ne= A @ &ile. 5his brings up a "ialog
=here you 'an 'on&igure =hat this A @ shoul" look an" =ork like
+1
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
49/747
Ho* To Get Starte
$igure 12 ing a ?e* >0
?ou nee" to pro!i"e the &ollo=ing
A name &or the A @. %in'e the name goes into &iles on your"e!elopment ma'hine, you =ill be limite" by &ilename 'on!entions&or your operating system (e.g., no ba'kslashes on Win"o=s).
5he An"roi" !ersion you =ant the emulator to run (a.k.a., theNtargetN). Choose one o& the %@Ds you installe" !ia the "rop-"o=nlist. ote that in a""ition to NpureN An"roi" en!ironments, you =illha!e options base" on the thir"-party a""-ons you sele'te". *ore;ample, you probably ha!e some options &or setting up A @s
'ontaining the oogle A# s, an" you =ill nee" su'h an A @ &ortesting an appli'ation that uses oogle Maps.
@etails about the %@ 'ar" the emulator shoul" emulate. %in'e An"roi" "e!i'es in!ariably ha!e some &orm o& Ne;ternal storageN, you probably =ant to set up an %@ 'ar", by supplying a si e in theasso'iate" &iel". +o=e!er, sin'e a &ile =ill be 'reate" on your
+3
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
50/747
Ho* To Get Starte
"e!elopment ma'hine o& =hate!er si e you spe'i&y &or the 'ar", youprobably "o not =ant to 'reate a 2 emulate" %@ 'ar". /2M is ani'e starting point, though you 'an go larger i& nee"e".
5he NskinN or resolution the emulator shoul" run in. 5he skinoptions you ha!e =ill "epen" upon =hat target you 'hose. 5he skinslet you 'hoose a typi'al An"roi" s'reen resolution (e.g., W A800&or 800; @N label
+6
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
51/747
Ho* To Get Starte
$igure 32 n roi emulator@ initial startup segment
...then a graphi'al An"roi" logo
+8
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
52/747
Ho* To Get Starte
$igure 62 n roi emulator@ secon ary startup segment
be&ore e!entually lan"ing at the home s'reen (the &irst time you run the A @, sho=n belo=) or the keyguar"
+:
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
53/747
Ho* To Get Starte
$igure 82 n roi home screen
& you get the keyguar" (sho=n belo=), press the ME $ button, or sli"e thegreen lo'k on the s'reen to the right, to get to the emulator7s home s'reen
(;
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
54/747
Ho* To Get Starte
$igure :2 n roi keyguar
Set =p the 0evice
?ou "o not nee" an An"roi" "e!i'e to get starte" in An"roi" appli'ation"e!elopment. +a!ing one is a goo" i"ea be&ore you try to ship anappli'ation (e.g., uploa" it to the An"roi" Market). An", perhaps youalrea"y ha!e a "e!i'e S maybe that is =hat is spurring your interest in"e!eloping &or An"roi".
5he &irst step to make your "e!i'e rea"y &or use =ith "e!elopment is to gointo the %ettings appli'ation on the "e!i'e. *rom there, 'hoose Appli'ations, then @e!elopment. 5hat shoul" gi!e you a set o& 'he'kbo;eso& "e!elopment-relate" options to 'onsi"er
(+
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
55/747
Ho* To Get Starte
$igure +;2 n roi evice evelopment settings
enerally, you =ill =ant to enable $% "ebugging, so you 'an use your"e!i'e =ith the An"roi" buil" tools. ?ou 'an lea!e the other settings alone&or no= i& you =ish, though you may &in" the N%tay a=akeN option to be
han"y, as it sa!es you &rom ha!ing to unlo'k your phone all o& the time =hile it is plugge" into $% .
e;t, you nee" to get your "e!elopment ma'hine set up to talk to your"e!i'e. 5hat pro'ess !aries by the operating system o& your "e!elopmentma'hine, as is 'o!ere" in the &ollo=ing se'tions.
,indo#s
When you &irst plug in your An"roi" "e!i'e, Win"o=s =ill attempt to &in" a"ri!er &or it. t is possible that, by !irtue o& other so&t=are you ha!einstalle", that the "ri!er is rea"y &or use. & it &in"s a "ri!er, you areprobably rea"y to go.
((
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
56/747
Ho* To Get Starte
& the "ri!er is not &oun", here are some options &or getting one.
Windows Update
%ome !ersions o& Win"o=s (e.g., ista) =ill prompt you to sear'h Win"o=s$p"ate &or "ri!ers. 5his is 'ertainly =orth a shot, though not e!ery "e!i'e =ill ha!e supplie" its "ri!er to Mi'roso&t.
Standard Android Driver
n your An"roi" %@D installation, you =ill &in" a google-usb driver"ire'tory, 'ontaining a generi' Win"o=s "ri!er &or An"roi" "e!i'es. ?ou
'an try pointing the "ri!er =i ar" at this "ire'tory to see i& it thinks this"ri!er is suitable &or your "e!i'e.
Manufacturer-Supplied Driver
& you still "o not ha!e a "ri!er, sear'h the C@ that 'ame =ith the "e!i'e (i&any) or sear'h the Web site o& the "e!i'e manu&a'turer. Motorola , &ore;ample, has "ri!ers a!ailable &or all o& their "e!i'es in one spot &or"o=nloa".
+S - nd )inu.
>""s are "e'ent that simply plugging in your "e!i'e =ill NHust =orkN. ?ou'an see i& An"roi" re'ogni es your "e!i'e !ia running adb devices in a shell(e.g., >% F 5erminal), =here adb is in your platform-tools/ "ire'tory o& your%@D. & you get output similar to the &ollo=ing, An"roi" "ete'te" your"e!i'e
)ist of devices attached!& +((, 0 device
& you are running $buntu (or perhaps other Linu; !ariants), an" this'omman" "i" not =ork, you may nee" to a"" some udev rules. *or e;ample,
(.
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
http://developer.motorola.com/docstools/USB_Drivers/http://developer.motorola.com/docstools/USB_Drivers/8/12/2019 Android 3 7 CC
57/747
Ho* To Get Starte
here is a 1-android.rules &ile that =ill han"le the "e!i'es &rom a han"&ul o&manu&a'turers
234252&$#667usb78 25292 idVendor;667 bb
8/12/2019 Android 3 7 CC
58/747
CHAPTER /
/our $irst n roi ProAect
o= that you ha!e the An"roi" %@D, it is time to make your &irst An"roi"proHe't. 5he goo" ne=s is that this reBuires ero lines o& 'o"e S An"roi"7stools 'reate a N+ello, =orl":N appli'ation &or you as part o& 'reating a ne=proHe't. All you nee" to "o is buil" it, install it, an" see it 'ome up on youremulator or "e!i'e.
Step + Create the ?e* ProAect
An"roi"7s tools 'an 'reate a 'omplete skeleton proHe't &or you, =ith
e!erything you nee" &or a 'omplete (albeit !ery tri!ial) An"roi" appli'ation.5he only real "i&&eren'e 'omes &rom =hether you are using E'lipse or the'omman" line.
Eclipse
*rom the E'lipse main menu, 'hoose *ile U e= U #roHe't..., an" this =illbring up a list o& proHe't types to 'hoose &rom. *ol" open the An"roi"option an" 'li'k on An"roi" #roHe't
(1
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
59/747
/our $irst n roi ProAect
$igure ++2
8/12/2019 Android 3 7 CC
60/747
/our $irst n roi ProAect
$igure +(2
8/12/2019 Android 3 7 CC
61/747
/our $irst n roi ProAect
$igure +.2
8/12/2019 Android 3 7 CC
62/747
/our $irst n roi ProAect
$igure +'2
8/12/2019 Android 3 7 CC
63/747
/our $irst n roi ProAect
5he name o& the a!a pa'kage in =hi'h this proHe't goes (e.g.,com.commonsDare.android.skeleton ) in the N#a'kage nameN &iel"
5he name o& the initial a'ti!ity to 'reate (e.g., o=) in the NCreate A'ti!ityN &iel"
At this point, 'li'king *inish =ill 'reate your E'lipse proHe't.
Comm nd )ine
+ere is a sample 'omman" that 'reates an An"roi" proHe't &rom the'omman" line
android create project --target 7Eoogle Inc.:Eoogle A(Is: 7 --path 2keleton/%oD--activitF %oD --package com . commonsDare . android . skeleton
5his =ill 'reate an appli'ation skeleton &or you, 'omplete =ith e!erything you nee" to buil" your &irst An"roi" appli'ation a!a sour'e 'o"e, buil"instru'tions, et'. +o=e!er, you are probably going to nee" to 'ustomi ethis some=hat. +ere are =hat those 'omman"-line s=it'hes mean
--target in"i'ates =hat !ersion o& An"roi" you are NtargetingN interms o& your buil" pro'ess. ?ou nee" to supply the @ o& a target
that is installe" on your "e!elopment ma'hine, one you"o=nloa"e" !ia the %@D an" A @ Manager. ?ou 'an &in" out =hattargets are a!ailable !ia the android list targets 'omman".5ypi'ally, your buil" pro'ess =ill target the ne=est !ersion o& An"roi" that you ha!e a!ailable.
--path in"i'ates =here you =ant the proHe't &iles to be generate". An"roi" =ill 'reate a "ire'tory i& the one you name "oes not e;ist.*or e;ample, in the 'omman" sho=n abo!e, a 2keleton/%oD/"ire'tory =ill be 'reate" (or use" i& it e;ists) un"erneath the 'urrent
=orking "ire'tory, an" the proHe't &iles =ill be store" there. --activitF in"i'ates the a!a 'lass name o& your &irst a'ti!ity &or this
proHe't. @o not in'lu"e a pa'kage name, an" the name has to meet a!a 'lass naming 'on!entions.
.;
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
64/747
/our $irst n roi ProAect
--package in"i'ates the a!a pa'kage in =hi'h your &irst a'ti!ity =illbe lo'ate". 5his pa'kage also uniBuely i"enti&ies your proHe't on any"e!i'e on =hi'h you install it, an" this pa'kage also nee"s to beuniBue on the An"roi" Market i& you plan on "istributing your
appli'ation there. +en'e, typi'ally, you 'onstru't your pa'kagebase" on a "omain name you o=n (e.g.,com.commonsDare.android.skeleton ), to re"u'e the o""s o& ana''i"ental pa'kage name 'ollision =ith somebo"y else.
*or your "e!elopment ma'hine, you =ill nee" to pi'k a suitable target, an" you may =ish to 'hange the path. 5he a'ti!ity an" pa'kage you 'an lea!ealone &or no=.
Step ( Buil @ "nstall@ an 4un the pplica%tion in /our n'e again, the pro'ess "i&&ers some=hat "epen"ing on =hether you areusing E'lipse or not.
Eclipse
With your proHe't sele'te" in the #a'kage E;plorer pane, 'li'k the greenNplayN button in the E'lipse toolbar to run your proHe't. 5he &irst time you"o this, you =ill ha!e to go through a &e= steps to set up a Nrun'on&igurationN, so E'lipse kno=s =hat you =ant to "o.
*irst, in the N un AsN list, 'hoose NAn"roi" Appli'ationN
.+
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
65/747
/our $irst n roi ProAect
$igure +12
8/12/2019 Android 3 7 CC
66/747
/our $irst n roi ProAect
setupB %o librarF dependencies. setupB
setupB ------------------ setupB
setupB @A?%I%E: %o min2dkVersion value set. Application Dill install on allAndroid versions. setupB
setupB Importing rules file: tools/ant/main rules.Gml
clean: deleteB =eleting directorF /home/some-balding-guF/projects/2keleton/%oD/bin deleteB =eleting directorF /home/some-balding-guF/projects/2keleton/%oD/gen
-debug-obfuscation-check:
-set-debug-mode:
-compile-tested-if-test:
-pre-build:-dirs: echoB +reating output directories if needed... mkdirB +reated dir: /home/some-balding-guF/projects/2keleton/%oD/bin mkdirB +reated dir: /home/some-balding-guF/projects/2keleton/%oD/gen mkdirB +reated dir: /home/some-balding-guF/projects/2keleton/%oD/bin/classes
-aidl: echoB +ompiling aidl files into Java classes...
-renderscript: echoB +ompiling ?ender2cript files into Java classes and ?ender2criptbFtecode...
-resource-src: echoB Eenerating ?.java / #anifest.java from the resources...
-pre-compile:
compile: javacB /opt/android-sdk-linuG/tools/ant/main rules.Gml:C, source files to /home/some-balding-guF/projects/2keleton/%oD/bin/classes
-post-compile:
-obfuscate:
-deG: echoB +onverting compiled files and eGternal libraries into /home/some-balding-guF/projects/2keleton/%oD/bin/classes.deG...
..
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
67/747
/our $irst n roi ProAect
-package-resources: echoB (ackaging resources aaptB +reating full resource package...
-package-debug-sign:apkbuilderB +reating %oD-debug-unaligned.apk and signing it Dith a debug keF...
debug: echoB ?unning Kip align on final apk... echoB =ebug (ackage: /home/some-balding-guF/projects/2keleton/%oD/bin/%oD-debug.apk
install: echoB Installing /home/some-balding-guF/projects/2keleton/%oD/bin/%oD-debug.apk onto default emulator or device... eGecB , H4/s L0 bFtes in . < sM eGecB pkg: /data/local/tmp/%oD-debug.apk eGecB 2uccess
43I)= 23++$2293)&otal time: 1 seconds
ote the 43I)= 23++$2293) at the bottom S that is ho= you kno= theappli'ation 'ompile" su''ess&ully.
When you ha!e a 'lean buil", in your emulator or "e!i'e, open up theappli'ation laun'her, typi'ally &oun" at the bottom o& the home s'reen
.'
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
68/747
/our $irst n roi ProAect
$igure +32 n roi emulator application launcher
oti'e there is an i'on &or your %oD appli'ation. Cli'k on it to open it an"see your &irst a'ti!ity in a'tion. 5o lea!e the appli'ation an" return to thelaun'her, press the N ACD buttonN, lo'ate" to the right o& the VME $button, an" looks like an arro= pointing to the le&t.
.1
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
69/747
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
70/747
CHAPTER 0
8/12/2019 Android 3 7 CC
71/747
8/12/2019 Android 3 7 CC
72/747
8/12/2019 Android 3 7 CC
73/747
8/12/2019 Android 3 7 CC
74/747
8/12/2019 Android 3 7 CC
75/747
8/12/2019 Android 3 7 CC
76/747
8/12/2019 Android 3 7 CC
77/747
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
78/747
CHAPTER 5
Bit bout
8/12/2019 Android 3 7 CC
79/747
Bit bout
8/12/2019 Android 3 7 CC
80/747
Bit bout
8/12/2019 Android 3 7 CC
81/747
Bit bout
8/12/2019 Android 3 7 CC
82/747
Bit bout
8/12/2019 Android 3 7 CC
83/747
Bit bout ther... &rom the main menu
1;
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
84/747
Bit bout
8/12/2019 Android 3 7 CC
85/747
Bit bout
8/12/2019 Android 3 7 CC
86/747
Bit bout
8/12/2019 Android 3 7 CC
87/747
Bit bout 0 ,anager menu option in
8/12/2019 Android 3 7 CC
88/747
Bit bout
8/12/2019 Android 3 7 CC
89/747
Bit bout
8/12/2019 Android 3 7 CC
90/747
CHAPTER 7
8/12/2019 Android 3 7 CC
91/747
ersions
As =as note" in the pre!ious 'hapter, your mani&est alrea"y 'ontains some !ersion in&ormation, about your o=n appli'ation7s !ersion. +o=e!er, you
probably =ant to a"" a Nuses-sdkO element as a 'hil" o& the NmanifestOelement to your Android#anifest.Gml &ile, to spe'i&y =hat !ersions o& An"roi" you are supporting. y "e&ault, your appli'ation is assume" tosupport e!ery An"roi" !ersion &rom 1.0 to the 'urrent /.0 an" on=ar" toany !ersion in the &uture. Most likely, that is not =hat you =ant.
5he most important attribute &or your Nuses-sdkO element isandroid:min2dkVersion . 5his in"i'ates =hat is the ol"est !ersion o& An"roi" you are testing =ith your appli'ation. 5he !alue o& the attribute is an
integer representing the An"roi" %@D !ersion An"roi" 1.0 X 1 An"roi" 1.1 X 2 An"roi" 1. X / An"roi" 1.4 X < An"roi" 2.0 X An"roi" 2.0.1 X 4 An"roi" 2.1 X An"roi" 2.2 X 8 An"roi" 2./ X 3 An"roi" 2././ X 10
18
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
92/747
8/12/2019 Android 3 7 CC
93/747
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
94/747
PART II Activities
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
95/747
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
96/747
CHAPTER 8
4e*riting /our $irst ProAect
5he proHe't you 'reate" in a pre!ious 'hapter =as Hust the "e&ault &ilesgenerate" by the An"roi" buil" tools S you "i" not =rite any a!a 'o"e yoursel&. n this 'hapter, =e =ill mo"i&y that proHe't to ha!e a some=hatmore intera'ti!e sample. Along the =ay, =e =ill e;amine the basi' a!a'o"e that makes up an An"roi" a'ti!ity.
>5E 5he instru'tions in this 'hapter assume you &ollo=e" the original instru'tions in terms o& the names o& pa'kages an" &iles. & you use""i&&erent names ba'k then, you =ill nee" to a"Hust the &ollo=ing steps tomat'h.
The ctivity
?our proHe't7s src/ "ire'tory 'ontains the stan"ar" a!a-style tree o&"ire'tories base" upon the a!a pa'kage you 'hose =hen you 'reate" theproHe't (e.g., com.commonsDare.android results insrc/com/commonsDare/android/ ). nsi"e the innermost "ire'tory you shoul"&in" a pre-generate" sour'e &ile name" %oD.java , =hi'h is =here your &irst
a'ti!ity =ill go.
>pen %oD.java in your e"itor an" paste in the &ollo=ing 'o"e
package com . commonsDare . android . skeleton
import android . app . ActivitF
3.
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
97/747
4e*riting /our $irst ProAect
import android . os . 4undleimport android . vieD . VieDimport android . Didget . 4uttonimport java . util . =ate
public class %oD eGtends ActivitF implements VieD . "n+lick)istener 4utton btn
Q"verride public void onCreate L4undle icicle M super . onCreate Licicle M
btn 6neD Button Lthis M btn . setOnClickListener Lthis M updateTime LM setContentView Lbtn M ;
public void onClick LVieD vieD M
updateTime LM ;
private void updateTime LM btn . setText LneD Date LM.toString LMM ;;
>r, i& you "o=nloa" the sour'e &iles o&& the Web site , you 'an Hust use the2keleton/%oD proHe't "ire'tly.
0issecting the ctivity
Let7s e;amine this a!a 'o"e pie'e by pie'e
package com . commonsDare . android . skeleton
import android . app . ActivitFimport android . os . 4undleimport android . vieD . VieDimport android . Didget . 4uttonimport java . util . =ate
5he pa'kage "e'laration nee"s to be the same as the one you use" =hen'reating the proHe't. An", like any other a!a proHe't, you nee" to importany 'lasses you re&eren'e. Most o& the An"roi"-spe'i&i' 'lasses are in theandroid pa'kage.
3'
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
http://commonsware.com/Android/http://commonsware.com/Android/8/12/2019 Android 3 7 CC
98/747
4e*riting /our $irst ProAect
emember that not e!ery a!a %E 'lass is a!ailable to An"roi" programs: isit the An"roi" 'lass re&eren'e to see =hat is an" is not a!ailable.
public class %oD eGtends ActivitF implements VieD . "n+lick)istener 4utton btn
A'ti!ities are publi' 'lasses, inheriting &rom the android.app.ActivitF base'lass. n this 'ase, the a'ti!ity hol"s a button ( btn ). %in'e, &or simpli'ity, =e =ant to trap all button 'li'ks Hust =ithin the a'ti!ity itsel&, =e also ha!e thea'ti!ity 'lass implement "n+lick)istener .
Q"verride public void onCreate L4undle icicle M super . onCreate Licicle M
btn 6neD Button Lthis M btn . setOnClickListener Lthis M updateTime LM setContentView Lbtn M ;
5he on+reateLM metho" is in!oke" =hen the a'ti!ity is starte". 5he &irstthing you shoul" "o is 'hain up=ar" to the super'lass, so the sto'k An"roi"a'ti!ity initiali ation 'an be "one.
n our implementation, =e then 'reate the button instan'e ( neD4uttonLthisM ), tell it to sen" all button 'li'ks to the a'ti!ity instan'e itsel&(!ia set"n+lick)istenerLM ), 'all a pri!ate update&imeLM metho" (see belo=),an" then set the a'ti!ity7s 'ontent !ie= to be the button itsel& (!iaset+ontentVieDLM ).
We =ill "is'uss that magi'al 4undle icicle in a later 'hapter. *or themoment, 'onsi"er it an opaBue han"le that all a'ti!ities re'ei!e upon'reation.
public void onClick LVieD vieD M updateTime LM;
n %=ing, a J4utton 'li'k raises an Action$vent , =hi'h is passe" to theAction)istener 'on&igure" &or the button. n An"roi", a button 'li'k 'auses
31
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
http://code.google.com/android/reference/packages.htmlhttp://code.google.com/android/reference/packages.htmlhttp://code.google.com/android/reference/packages.html8/12/2019 Android 3 7 CC
99/747
4e*riting /our $irst ProAect
on+lickLM to be in!oke" in the "n+lick)istener instan'e 'on&igure" &or thebutton. 5he listener is pro!i"e" the !ie= that triggere" the 'li'k (in this'ase, the button). All =e "o here is 'all that pri!ate update&imeLM metho"
private void updateTime LM btn . setText LneD Date LM.toString LMM;
When =e open the a'ti!ity ( on+reateLM ) or =hen the button is 'li'ke"(on+lickLM ), =e up"ate the button7s label to be the 'urrent time !iaset&eGtLM, =hi'h &un'tions mu'h the same as the J4utton eBui!alent.
Buil ing an 4unning the ctivity
5o buil" the a'ti!ity, either use your @E7s built-in An"roi" pa'kaging tool,or run ant clean debug install in the base "ire'tory o& your proHe't. 5hen,run the a'ti!ity S it shoul" be automati'ally laun'he" &or you i& you areusing E'lipse, else &in" the a'ti!ity in the home s'reen laun'her. ?ou shoul"see an a'ti!ity akin to
$igure (32 The ?o* emonstration activity
33
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
100/747
4e*riting /our $irst ProAect
Cli'king the button S in other =or"s, pretty mu'h any=here on the phone7ss'reen S =ill up"ate the time sho=n in the button7s label.
ote that the label is 'entere" hori ontally an" !erti'ally, as those are the"e&ault styles applie" to button 'aptions. We 'an 'ontrol that &ormatting, =hi'h =ill be 'o!ere" in a later 'hapter .
A&ter you are "one ga ing at the a=esomeness o& A"!an'e" #ush- utton5e'hnologyY, you 'an 'li'k the ba'k button on the emulator to return tothe laun'her.
bout the 4emaining
8/12/2019 Android 3 7 CC
101/747
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
102/747
CHAPTER 9
=sing F,#%Base #ayouts
While it is te'hni'ally possible to 'reate an" atta'h =i"gets to our a'ti!itypurely through a!a 'o"e, the =ay =e "i" in the pre'e"ing 'hapter , themore 'ommon approa'h is to use an FML-base" layout &ile. @ynami'instantiation o& =i"gets is reser!e" &or more 'ompli'ate" s'enarios, =herethe =i"gets are not kno=n at 'ompile-time (e.g., populating a 'olumn o&ra"io buttons base" on "ata retrie!e" o&& the nternet).
With that in min", it7s time to break out the FML an" learn ho= to lay out An"roi" a'ti!ity !ie=s that =ay.
What "s an F,#%Base #ayout
As the name suggests, an FML-base" layout is a spe'i&i'ation o& =i"gets7relationships to ea'h other S an" to 'ontainers S en'o"e" in FML &ormat.%pe'i&i'ally, An"roi" 'onsi"ers FML-base" layouts to be resour'es, an" assu'h layout &iles are store" in the res/laFout "ire'tory insi"e your An"roi"proHe't.
Ea'h FML &ile 'ontains a tree o& elements spe'i&ying a layout o& =i"gets an"'ontainers that make up one VieD. 5he attributes o& the FML elements areproperties, "es'ribing ho= a =i"get shoul" look or ho= a 'ontainer shoul"beha!e. *or e;ample, i& a 4utton element has an attribute !alue o&android:teGt2tFle 6 7bold7 , that means that the te;t appearing on the &a'eo& the button shoul" be ren"ere" in a bol"&a'e &ont style.
3:
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
103/747
=sing F,#%Base #ayouts
An"roi"7s %@D ships =ith a tool ( aapt ) =hi'h uses the layouts. 5his toolshoul" be automati'ally in!oke" by your An"roi" tool 'hain (e.g., E'lipse, Ant7s build.Gml ). >& parti'ular importan'e to you as a "e!eloper is that aaptgenerates the ?.java sour'e &ile =ithin your proHe't7s gen/ "ire'tory,
allo=ing you to a''ess layouts an" =i"gets =ithin those layouts "ire'tly&rom your a!a 'o"e, as =ill be "emonstrate" later in this 'hapter.
Why =se F,#%Base #ayouts
Almost e!erything you "o using FML layout &iles 'an be a'hie!e" through a!a 'o"e. *or e;ample, you 'oul" use set&FpefaceLM to ha!e a buttonren"er its te;t in bol", instea" o& using a property in an FML layout. %in'e FML layouts are yet another &ile &or you to keep tra'k o&, =e nee" goo"reasons &or using su'h &iles.
#erhaps the biggest reason is to assist in the 'reation o& tools &or !ie="e&inition, su'h as a $ buil"er in an @E like E'lipse or a "e"i'ate" An"roi" $ "esigner like @roi"@ra=. %u'h $ buil"ers 'oul", inprin'iple, generate a!a 'o"e instea" o& FML. 5he 'hallenge is re-rea"ingthe "e&inition in to support e"its S that is &ar simpler i& the "ata is in astru'ture" &ormat like FML than in a programming language. Moreo!er,keeping the generate" bits separate" out &rom han"-=ritten 'o"e makes itless likely that somebo"y7s 'ustom-'ra&te" sour'e =ill get 'lobbere" bya''i"ent =hen the generate" bits get re-generate". FML &orms a ni'emi""le groun" bet=een something that is easy &or tool-=riters to use an"easy &or programmers to =ork =ith by han" as nee"e".
Also, FML as a $ "e&inition &ormat is be'oming more 'ommonpla'e.Mi'roso&t7s FAML, A"obe7s *le; , oogle7s W5, an" Mo illa7s F$L all takea similar approa'h to that o& An"roi" put layout "etails in an FML &ile an"put programming smarts in sour'e &iles (e.g., a!as'ript &or F$L). Manyless-=ell-kno=n $ &rame=orks, su'h as RD, also use FML &or !ie="e&inition. While N&ollo=ing the her"N is not ne'essarily the best poli'y, it"oes ha!e the a"!antage o& helping to ease the transition into An"roi" &romany other FML-'entere" !ie= "es'ription language.
6;
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
http://droiddraw.org/http://windowssdk.msdn.microsoft.com/en-us/library/ms752059.aspxhttp://www.adobe.com/products/flex/http://www.adobe.com/products/flex/http://www.mozilla.org/projects/xul/http://www.zkoss.org/http://droiddraw.org/http://windowssdk.msdn.microsoft.com/en-us/library/ms752059.aspxhttp://www.adobe.com/products/flex/http://www.mozilla.org/projects/xul/http://www.zkoss.org/8/12/2019 Android 3 7 CC
104/747
=sing F,#%Base #ayouts
-9@ So What 0oes "t #ook #ike
+ere is the 4utton &rom the pre!ious 'hapter7s sample appli'ation,'on!erte" into an FML layout &ile, &oun" in the )aFouts/%oD?eduG sampleproHe't
NPGml version 671. 7 encoding 67utf-,7 PON4utton Gmlns:android 67http://schemas.android.com/apk/res/android7 android:id 67QRid/button7 android:teGt 677 android:laFout Didth 67fill parent7 android:laFout height 67fill parent7 /O
5he 'lass name o& the =i"get S 4utton S &orms the name o& the FMLelement. %in'e 4utton is an An"roi"-supplie" =i"get, =e 'an Hust use thebare 'lass name. & you 'reate your o=n =i"gets as sub'lasses o&android.vieD.VieD , you =oul" nee" to pro!i"e a &ull pa'kage "e'laration as =ell (e.g., com.commonsDare.android.#F@idget ).
5he root element nee"s to "e'lare the An"roi" FML namespa'e
Gmlns:android67http://schemas.android.com/apk/res/android7
All other elements =ill be 'hil"ren o& the root an" =ill inherit thatnamespa'e "e'laration.
e'ause =e =ant to re&eren'e this button &rom our a!a 'o"e, =e nee" togi!e it an i"enti&ier !ia the android:id attribute. We =ill 'o!er this 'on'eptin greater "etail later in this 'hapter.
5he remaining attributes are properties o& this 4utton instan'e
android:teGt in"i'ates the initial te;t to be "isplaye" on the button&a'e (in this 'ase, an empty string)
android:laFout Didth an" android:laFout height tell An"roi" to ha!ethe button7s =i"th an" height &ill the NparentN, in this 'ase the entires'reen S these attributes =ill be 'o!ere" in greater "etail in a later 'hapter
6+
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
105/747
=sing F,#%Base #ayouts
%in'e this single =i"get is the only 'ontent in our a'ti!ity7s !ie=, =e onlynee" this single element. Comple; !ie=s =ill reBuire a =hole tree o&elements, representing the =i"gets an" 'ontainers that 'ontrol theirpositioning. All the remaining 'hapters o& this book =ill use the FML layout
&orm =hene!er pra'ti'al, so there are "o ens o& other e;amples o& more'omple; layouts &or you to peruse.
What s With the I Signs
Many =i"gets an" 'ontainers only nee" to appear in the FML layout &ilean" "o not nee" to be re&eren'e" in your a!a 'o"e. *or e;ample, a stati'label ( &eGtVieD) &reBuently only nee"s to be in the layout &ile to in"i'ate =here it shoul" appear. 5hese sorts o& elements in the FML &ile "o not nee"to ha!e the android:id attribute to gi!e them a name.
Anything you do =ant to use in your a!a sour'e, though, nee"s anandroid:id .
5he 'on!ention is to use QRid/... as the id !alue, =here the ... represents your lo'ally-uniBue name &or the =i"get in Buestion, &or the &irsto''urren'e o& a gi!en id !alue in your layout &ile. 5he se'on" an"
subseBuent o''urren'es in the same layout &ile shoul" "rop the R sign S a&eature =e =ill use in an up'oming 'hapter . n the FML layout e;ample inthe pre'e"ing se'tion, QRid/button is the i"enti&ier &or the 4utton =i"get.
An"roi" pro!i"es a &e= spe'ial android:id !alues, o& the &ormQandroid:id/... S =e =ill see some o& these in !arious 'hapters o& this book.
n We ttach These to the 7ava222Ho*
i!en that you ha!e painstakingly set up the =i"gets an" 'ontainers &or your !ie= in an FML layout &ile name" main.Gml store" in res/laFout , all younee" is one statement in your a'ti!ity7s on+reateLM 'allba'k to use thatlayout
6(
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
106/747
=sing F,#%Base #ayouts
setContentView L?. laFout . main M
5his is the same set+ontentVieDLM =e use" earlier, passing it an instan'e o& aVieD sub'lass (in that 'ase, a 4utton ). 5he An"roi"-built VieD, 'onstru'te"
&rom our layout, is a''esse" &rom that 'o"e-generate" ? 'lass. All o& thelayouts are a''essible un"er ?.laFout , keye" by the base name o& the layout&ile Sres/laFout/main.Gml results in ?.laFout.main .
5o a''ess our i"enti&ie" =i"gets, use findVieD4FIdLM , passing it the numeri'i"enti&ier o& the =i"get in Buestion. 5hat numeri' i"enti&ier =as generate"by An"roi" in the ? 'lass as ?.id.something (=here something is the spe'i&i' =i"get you are seeking). 5hose =i"gets are simply sub'lasses o& VieD, Hustlike the 4utton instan'e =e 'reate" in the pre!ious 'hapter.
The 4est of the Story
n the original %oD "emo, the button7s &a'e =oul" sho= the 'urrent time, =hi'h =oul" re&le't =hen the button =as last pushe" (or =hen the a'ti!ity =as &irst sho=n, i& the button ha" not yet been pushe").
Most o& that logi' still =orks, e!en in this re!ise" "emo ( %oD?eduG).
+o=e!er, rather than instantiating the 4utton in our a'ti!ity7s on+reateLM'allba'k, =e 'an re&eren'e the one &rom the FML layout
package com . commonsDare . android . laFouts
import android . app . ActivitFimport android . os . 4undleimport android . vieD . VieDimport android . Didget . 4uttonimport java . util . =ate
public class %oD?eduG eGtends ActivitF implements VieD . "n+lick)istener 4utton btn
Q"verride public void onCreate L4undle icicle M super . onCreate Licicle M
setContentView L?. laFout . main M
6.
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
107/747
=sing F,#%Base #ayouts
btn 6L4utton MfindViewById L?. id . button M btn . setOnClickListener Lthis M updateTime LM ;
public void onClick LVieD vieD M updateTime LM ;
private void updateTime LM btn . setText LneD Date LM.toString LMM ;;
5he &irst "i&&eren'e is that rather than setting the 'ontent !ie= to be a !ie= =e 'reate" in a!a 'o"e, =e set it to re&eren'e the FML layout(set+ontentVieDL?.laFout.mainM ). 5he ?.java sour'e &ile =ill be up"ate"
=hen =e rebuil" this proHe't to in'lu"e a re&eren'e to our layout &ile (store"as main.Gml in our proHe't7s res/laFout "ire'tory).
5he other "i&&eren'e is that =e nee" to get our han"s on our 4uttoninstan'e, &or =hi'h =e use the findVieD4FIdLM 'all. %in'e =e i"enti&ie" ourbutton as QRid/button , =e 'an re&eren'e the button7s i"enti&ier as?.id.button . o=, =ith the 4utton instan'e in han", =e 'an set the 'allba'kan" set the label as nee"e".
5he results look the same as =ith the original %oD "emo
6'
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
108/747
=sing F,#%Base #ayouts
$igure (62 The ?o*4e ux sample activity
61
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
109/747
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
110/747
CHAPTER :
8/12/2019 Android 3 7 CC
111/747
8/12/2019 Android 3 7 CC
112/747
8/12/2019 Android 3 7 CC
113/747
8/12/2019 Android 3 7 CC
114/747
8/12/2019 Android 3 7 CC
115/747
8/12/2019 Android 3 7 CC
116/747
8/12/2019 Android 3 7 CC
117/747
8/12/2019 Android 3 7 CC
118/747
8/12/2019 Android 3 7 CC
119/747
8/12/2019 Android 3 7 CC
120/747
8/12/2019 Android 3 7 CC
121/747
8/12/2019 Android 3 7 CC
122/747
8/12/2019 Android 3 7 CC
123/747
mm is 2 millimeters. We =ill e;amine "imension in greater "etail
in an up'oming 'hapter .
+ther ;se ul Properties
n a""ition to those presente" in this 'hapter an" in the ne;t 'hapter , someo& the properties on VieD most likely to be use" in'lu"e
android:visibilitF , =hi'h 'ontrols =hether the =i"get is initially !isible
android:neGt9ocus=oDn , android:neGt9ocus)eft ,android:neGt9ocus?ight , an" android:neGt9ocus3p , =hi'h 'ontrol the&o'us or"er i& the user uses the @-pa", tra'kball, or similar pointing"e!i'e
:;
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
124/747
8/12/2019 Android 3 7 CC
125/747
8/12/2019 Android 3 7 CC
126/747
CHAPTER 1D an" Can'elbuttons to be beneath the rest o& the &orm, ne;t to one another, an" &lushto right si"e o& the s'reen, you =ill nee" a 'ontainer. ust &rom a pure FMLperspe'ti!e, i& you ha!e multiple =i"gets (beyon" ?adio4utton =i"gets in a?adioEroup ), you =ill nee" a 'ontainer Hust to ha!e a root element to pla'ethe =i"gets insi"e.
Most $ toolkits ha!e some notion o& layout management, &reBuentlyorgani e" into 'ontainers. n a!aQ%=ing, &or e;ample, you ha!e layoutmanagers like 4oG)aFout an" 'ontainers that use them (e.g., 4oG). %ometoolkits sti'k stri'tly to the bo; mo"el, su'h as F$L an" *le;, &iguring thatany "esire" layout 'an be a'hie!e" through the right 'ombination o& neste"bo;es.
An"roi", through )inear)aFout , also o&&ers a Nbo;N mo"el, but in a""itionsupports a range o& 'ontainers pro!i"ing "i&&erent layout rules. n this'hapter, =e =ill look at three 'ommonly-use" 'ontainers )inear)aFout (thebo; mo"el), ?elative)aFout (a rule-base" mo"el), an" &able)aFout (the gri"mo"el), along =ith 2crollVieD , a 'ontainer "esigne" to assist =ithimplementing s'rolling 'ontainers.
:.
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
127/747
8/12/2019 Android 3 7 CC
128/747
Working *ith Containers
All =i"gets insi"e a )inear)aFout must supply android:laFout Didth an"android:laFout height properties to help a""ress this issue. 5heseproperties7 !alues ha!e three &la!ors
?ou 'an pro!i"e a spe'i&i' "imension, su'h as1> dip
to in"i'ate the =i"get shoul" take up e;a'tly a 'ertain si e ?ou 'an pro!i"e Drap content , =hi'h means the =i"get shoul" &ill
up its natural spa'e, unless that is too big, in =hi'h 'ase An"roi"'an use =or"-=rap as nee"e" to make it &it
?ou 'an pro!i"e fill parent , =hi'h means the =i"get shoul" &ill upall a!ailable spa'e in its en'losing 'ontainer, a&ter all other =i"getsare taken 'are o&
5he latter t=o &la!ors are the most 'ommon, as they are in"epen"ent o&s'reen si e, allo=ing An"roi" to a"Hust your !ie= to &it the a!ailable spa'e.
@ T+ n A# le!el 8 (An"roi" 2.2), fill parent =as rename" tomatch parent , &or unkno=n reasons. ?ou 'an still use fill parent , as it =illbe supporte" &or the &oreseeable &uture. +o=e!er, at su'h point in time as you are only supporting A# le!el 8 or higher (e.g.,android:min2dkVersion67,7 in your mani&est), you shoul" probably s=it'ho!er to match parent .
Weight
ut, =hat happens i& =e ha!e t=o =i"gets that shoul" split the a!ailable&ree spa'eI *or e;ample, suppose =e ha!e t=o multi-line &iel"s in a 'olumn,an" =e =ant them to take up the remaining spa'e in the 'olumn a&ter allother =i"gets ha!e been allo'ate" their spa'e.
5o make this =ork, in a""ition to setting android:laFout Didth (&or ro=s) orandroid:laFout height (&or 'olumns) to fill parent , you must also setandroid:laFout Deight . 5his property in"i'ates =hat proportion o& the &reespa'e shoul" go to that =i"get. & you set android:laFout Deight to be thesame non- ero !alue &or a pair o& =i"gets (e.g., 1), the &ree spa'e =ill besplit e!enly bet=een them. & you set it to be 1 &or one =i"get an" > &or
:1
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
129/747
Working *ith Containers
another =i"get, the se'on" =i"get =ill use up t=i'e the &ree spa'e that the&irst =i"get "oes. An" so on.
5he =eight &or a =i"get is ero by "e&ault.
Another pattern &or using =eights is i& you =ant to allo'ate si es on aper'entage basis. 5o use this te'hniBue &or, say, a hori ontal layout
%et all the android:laFout Didth !alues to be &or the =i"gets in thelayout
%et the android:laFout Deight !alues to be the "esire" per'entagesi e &or ea'h =i"get in the layout
Make sure all those =eights a"" up to 1
ravit!
y "e&ault, e!erything in a )inear)aFout is le&t- an" top-aligne". %o, i& you'reate a ro= o& =i"gets !ia a hori ontal )inear)aFout , the ro= =ill start &lushon the le&t si"e o& the s'reen.
& that is not =hat you =ant, you nee" to spe'i&y a gra!ity. $nlike thephysi'al =orl", An"roi" has t=o types o& gra!ity the gra!ity o& a =i"get =ithin a )inear)aFout , an" the gra!ity o& the 'ontents o& a =i"get or'ontainer.
5he android:gravitF property o& some =i"gets an" 'ontainers S =hi'h also'an be "e&ine" !ia set ra!ity() in a!a S tells An"roi" to sli"e the 'ontentso& the =i"get or 'ontainer in a parti'ular "ire'tion. *or e;ample,android:gravitF67right7 says to sli"e the 'ontents o& the =i"get to the rightTandroid:gravitF67rightWbottom7 says to sli"e the 'ontents o& the =i"get tothe right an" the bottom.
+ere, N'ontentsN !aries. &eGtVieD supports android:gravitF , an" theN'ontentsN is the te;t hel" =ithin the &eGtVieD. )inear)aFout supportsandroid:gravitF , an" the N'ontentsN are the =i"gets insi"e the 'ontainer. An" so on.
:3
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
130/747
Working *ith Containers
Chil"ren o& a )inear)aFout also ha!e the option o& spe'i&yingandroid:laFout gravitF . +ere, the 'hil" is telling the )inear)aFout Ni& thereis room, please sli"e me (an" me alone) in this "ire'tionN.
*or e;ample, let7s suppose that =e ha!e a hori ontal )inear)aFout =iththree 'hil" =i"gets. y "e&ault, they =ill be le&t-aligne"
$igure .32 #inear#ayout *ith three chil ren@ left%aligne
& =e spe'i&ie" android:gravitF67right7 on the )inear)aFout , all three =i"gets =oul" sli"e o!er to the right
:6
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
131/747
8/12/2019 Android 3 7 CC
132/747
Working *ith Containers
*or a ro= o& =i"gets, the "e&ault is &or them to be aligne" so their te;ts arealigne" on the baseline (the in!isible line that letters seem to Nsit onN),though you may =ish to spe'i&y a gra!ity o& center vertical to 'enter the =i"gets along the ro=7s !erti'al mi"point.
Margins
y "e&ault, =i"gets are tightly pa'ke", one ne;t to the other. ?ou 'an'ontrol this !ia the use o& margins, a 'on'ept that is reminis'ent o& thepa""ing "es'ribe" in a pre!ious 'hapter .
5he "i&&eren'e bet=een pa""ing an" margins 'omes in terms o& the
ba'kgroun". Wi"gets =ith a transparent ba'kgroun" S like the "e&ault looko& a&eGtVieD S pa""ing an" margins ha!e similar !isual e&&e't, in'reasingthe spa'e bet=een the =i"get an" a"Ha'ent =i"gets. +o=e!er, =i"gets =itha non-transparent ba'kgroun" S like a 4utton S pa""ing is 'onsi"ere"insi"e the ba'kgroun" =hile margins are outsi"e. n other =or"s, a""ingpa""ing =ill in'rease the spa'e bet=een the 'ontents (e.g., the 'aption o& a4utton ) an" the e"ges, =hile a""ing margin in'reases the empty spa'ebet=een the e"ges an" a"Ha'ent =i"gets.
Margins 'an be set in FML, either on a per-si"e basis (e.g.,android:laFout margin&op ) or on all si"es !ia android:laFout margin . >n'eagain, the !alue o& any o& these is a "imension S a 'ombination o& a unit o&measure an" a 'ount, su'h as pG &or pi;els.
E. mple
Let7s look at an e;ample ( +ontainers/)inear ) that sho=s )inear)aFoutproperties set both in the FML layout &ile an" at runtime.
+ere is the layout
NPGml version 671. 7 encoding 67utf-,7 PON)inear)aFout Gmlns:android 67http://schemas.android.com/apk/res/android7 android:orientation 67vertical7
::
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
133/747
Working *ith Containers
android:laFout Didth 67fill parent7 android:laFout height 67fill parent7 O N?adioEroup android:id 67QRid/orientation7 android:orientation 67horiKontal7 android:laFout Didth 67Drap content7 android:laFout height 67Drap content7 android:padding 67 dip7 O N?adio4utton android:id 67QRid/horiKontal7 android:teGt 67horiKontal7 /O N?adio4utton android:id 67QRid/vertical7 android:teGt 67vertical7 /O N/?adioEroupO N?adioEroup android:id 67QRid/gravitF7 android:orientation 67vertical7 android:laFout Didth 67fill parent7 android:laFout height 67Drap content7
android:padding 67 dip7 O N?adio4utton android:id 67QRid/left7 android:teGt 67left7 /O N?adio4utton android:id 67QRid/center7 android:teGt 67center7 /O N?adio4utton android:id 67QRid/right7 android:teGt 67right7 /O N/?adioEroupON/)inear)aFoutO
ote that =e ha!e a )inear)aFout =rapping t=o ?adioEroup sets. ?adioEroupis a sub'lass o& )inear)aFout , so our e;ample "emonstrates neste" bo;es asi& they =ere all )inear)aFout 'ontainers.
5he top ?adioEroup sets up a ro= ( android:orientation 6 7horiKontal7 ) o&?adio4utton =i"gets. 5he ?adioEroup has dip o& pa""ing on all si"es,separating it &rom the other ?adioEroup , =here dip stan"s &or "ensity-in"epen"ent pi;els (think o& them as or"inary pi;els &or no= S =e =ill getinto the "istin'tion later in the book ). 5he =i"th an" height are both set toDrap content , so the ra"io buttons =ill only take up the spa'e that theynee".
5he bottom ?adioEroup is a 'olumn ( android:orientation 6 7vertical7 ) o&three ?adio4utton =i"gets. Again, =e ha!e dip o& pa""ing on all si"es an" aNnaturalN height (android:laFout height 6 7Drap content7 ). +o=e!er, =e
+;;
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
134/747
Working *ith Containers
ha!e set android:laFout Didth to be fill parent , meaning the 'olumn o&ra"io buttons N'laimsN the entire =i"th o& the s'reen.
5o a"Hust these settings at runtime base" on user input, =e nee" some a!a'o"e
package com . commonsDare . android . linear
import android . app . ActivitFimport android . os . 4undleimport android . vieD . EravitFimport android . teGt . &eGt@atcherimport android . Didget . )inear)aFoutimport android . Didget . ?adioEroupimport android . Didget . $dit&eGt
public class )inear)aFout=emo eGtends ActivitF implements ?adioEroup . "n+hecked+hange)istener ?adioEroup orientation ?adioEroup gravitF
Q"verride public void onCreate L4undle icicle M super . onCreate Licicle M setContentView L?. laFout . main M
orientation 6L?adioEroup MfindViewById L?. id . orientation M orientation . setOnCheckedChangeListener Lthis M gravitF 6L?adioEroup MfindViewById L?. id . gravitF M gravitF . setOnCheckedChangeListener Lthis M ;
public void onCheckedChanged L?adioEroup group 8 int checkedId M sDitch LcheckedId M case ? . id . horiKontal : orientation . setOrientation L)inear)aFout . !"?I "%&A) M break
case ? . id . vertical : orientation . setOrientation L)inear)aFout . V$?&I+A)M break
case ? . id . left :
gravitF . set ra!ity LEravitF . )$9&M break
case ? . id . center : gravitF . set ra!ity LEravitF . +$%&$? !"?I "%&A) M break
case ? . id . right :
+;+
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
135/747
Working *ith Containers
gravitF . set ra!ity LEravitF . ?IE!& M break ; ;;
n on+reateLM , =e look up our t=o ?adioEroup 'ontainers an" register alistener on ea'h, so =e are noti&ie" =hen the ra"io buttons 'hange state(set"n+hecked+hange)istenerLthisM ). %in'e the a'ti!ity implements"n+hecked+hange)istener , the a'ti!ity itsel& is the listener.
n on+hecked+hangedLM (the 'allba'k &or the listener), =e see =hi'h?adio4utton ha" a state 'hange. ase" on the 'li'ke"-upon item, =e a"Husteither the orientation o& the &irst )inear)aFout or the gra!ity o& the se'on"
)inear)aFout .
+ere is the result =hen it is &irst laun'he" insi"e the emulator
$igure .:2 The #inear#ayout0emo sample application@ as initially launche
& =e toggle on the N!erti'alN ra"io button, the top ?adioEroup a"Husts tomat'h
+;(
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
136/747
Working *ith Containers
$igure ';2 The same application@ *ith the vertical ra io button selecte
& =e toggle the N'enterN or NrightN ra"io buttons, the bottom ?adioEroupa"Husts to mat'h
$igure '+2 The same application@ *ith the vertical an center ra io buttonsselecte
+;.
Subscribe to updates at http://commonsware.com Special Creative Commons BY-NC-SA 3.0 License Edition
8/12/2019 Android 3 7 CC
137/747
Working *ith Containers
$igure '(2 The same application@ *ith the vertical an right ra io buttonsselecte
The Bo. %odel
As note" earlier in this 'hapter,