android 1 2 cc
TRANSCRIPT
-
8/13/2019 Android 1 2 CC
1/400
The Busy Coder's Guide to AndroidDevelopment
by Mark L. Murphy
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
2/400
The Busy Coder's Guide to Android Developmentby Mark L. Murphy
Copyright 2008 CommonsWare, LLC. All Rights Reserve.!rinte in the "nite #tates o$ Ameri%a.
CommonsWare books may be pur%hase in printe &bulk' or igital $orm $or eu%ational orbusiness use. (or more in$ormation, %onta%t [email protected].
!rinting )istory*#ep 2008* +ersion .2 -#/* 180831800
4he CommonsWare name an logo, 5usy Coer6s 7uie, an relate trae ress aretraemarks o$ CommonsWare, LLC.
All other traemarks re$eren%e in this book are traemarks o$ their respe%tive $irms.
4he 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-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
3/400
Table of Contents
Welcome to the Warescription!..................................................................................xiii
Preface..........................................................................................................................xv
Wel%ome to the ook9...........................................................................................................:v
!rere;uisites..................................................................................................................... .....:v
Wares%ription.......................................................................................................................:vi
ook ug ounty.................................................................................................................:vii
#our%e Coe Li%ense........................................................................................................ ..:viii
Creative Commons an the (ourto(ree &
-
8/13/2019 Android 1 2 CC
4/400
4he #=eat >$$ @our ro=................................................................................................... ....8
An /o=, 4he Rest o$ the #tory.............................................................................................8
What @ou 7et >ut >$ -t.........................................................................................................
%nside the &anifest........................................................................................................
-n 4he eginning, 4here Was the Root, An -t Was 7oo.................................................
!ermissions, -nstrumentations, an Appli%ations &>h, My9'.............................................2@our Appli%ation oes #omething, Right........................................................................ ..?
Creatin a #eleton Application...................................................................................$
egin at the eginning...........................................................................................................1
4he A%tivity............................................................................................................................8
isse%ting the A%tivity...........................................................................................................
uiling an Running the A%tivity.......................................................................................2
(sin )&*+Based *ayouts............................................................................................,-
What -s an DMLase Layout.......................................................................................... .2B
Why "se DMLase Layouts............................................................................................23
>E, #o What oes -t Look Like..........................................................................................21
What6s With the F #igns............................................................................................... .....28
An We Atta%h 4hese to the Gava...)o=...................................................................... .....28
4he Rest o$ the #tory.............................................................................................................2
mployin Basic Widets..............................................................................................//
Assigning Labels....................................................................................................................??
utton, utton, Who6s 7ot the utton..............................................................................?r >ther Colors.........................................................................................?3
Gust Another o: to Che%k....................................................................................... ............?
4urn the Raio "p............................................................................................................... .
-
8/13/2019 Android 1 2 CC
5/400
All 4hings Are Relative.........................................................................................................B3
Con%epts an !roperties...............................................................................................B3
I:ample..........................................................................................................................B
4abula Rasa............................................................................................................................32
Con%epts an !roperties...............................................................................................32
I:ample..........................................................................................................................3B#%roll=ork..............................................................................................................................33
(sin #election Widets...............................................................................................$
Aapting to the Cir%umstan%es........................................................................................ ....1
"sing ArrayAapter.......................................................................................................12
>ther Eey Aapters.......................................................................................................1?
Lists o$ /aughty an /i%e........................................................................................... .........1r #omething Like 4hat...'.....................................................................80
(iels* /o= With ?BJ Less 4yping9................................................................................ ....8r 4ake 4he Art...........................................................................................88
Gettin 2ancy With *ists..............................................................................................34
7etting 4o (irst ase............................................................................................................8
A ynami% !resentation.......................................................................................................2
A #iebar About -n$lation.............................................................................................ur #tory.......................................................................................n My 4ab...........................................................................................................22
4he !ie%es................................................................................................................. ....2?
4he -iosyn%rasies........................................................................................................2?
v
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
6/400
Wiring -t 4ogether............................................................................................. ..........2B
>ther Containers o$ /ote....................................................................................................28
Applyin &enus...........................................................................................................,4
(lavors o$ Menu....................................................................................................................2
Menus o$ >ptions....................................................................................................... .........?0
Menus in Conte:t.................................................................................................................?24aking a !eek........................................................................................................................??
m5eddin the We56it Bro0ser.................................................................................1
A ro=ser, Writ #mall..........................................................................................................
-
8/13/2019 Android 1 2 CC
7/400
#tating @our !re$eren%e.......................................................................................................1ur (rame=ork..........................................................................1B
Letting "sers )ave 4heir #ay..............................................................................................13
Aing a Wee it >6 #tru%ture......................................................................................... ...8
4he Ein >$ !op"ps @ou Like..................................................................................... .....8n.................................................................................8
Reain6 6n Writin6.............................................................................................................. ...?
Worin 0ith 9esources.............................................................................................4$
4he Resour%e Lineup........................................................................................................ ...1
#tring 4heory.................................................................................................................... ...8
!lain #trings........................................................................................................ .........8
#tring (ormats..............................................................................................................
#tyle 4e:t....................................................................................................................
#tyle (ormats.............................................................................................................200
7ot the !i%ture...................................................................................................................20n the plus sie, %ir%a 2008, Anroistyle smartphones are se:y. >$$ering-nternet servi%es over mobile evi%es ates ba%k to the mi06s an the)anhel evi%e Markup Language &)ML'. )o=ever, only in re%ent yearshave phones %apable o$ -nternet a%%ess taken o$$. /o=, thanks to trens likete:t messaging an to prou%ts like Apple6s i!hone, phones that %an serve as-nternet a%%ess evi%es are rapily gaining popularity. #o, =orking on
Anroi appli%ations gives you e:perien%e =ith an interesting te%hnology&Anroi' in a $astmoving market segment &-nternetenable phones',
=hi%h is al=ays a goo thing.
4he problem %omes =hen you a%tually have to program the arn things.
Anyone =ith e:perien%e in programming $or !As or phones has $elt thepain o$ phones simply being smallin all sorts o$ imensions*
#%reens are small &you =on6t get %omments like, Qis that a 2
-
8/13/2019 Android 1 2 CC
24/400
The Big Picture
!ointing evi%es, i$ they e:ist, are annoying &as anyone =ho has losttheir stylus =ill tell you' or ine:a%t &large $ingers an Qmultitou%hQLCs are not a goo mi:'
C!" spee an memory are tight %ompare to esktops an serversyou may be use to
@ou %an have any programming language an evelopment$rame=ork you =ant, so long as it =as =hat the evi%e manu$a%turer%hose an burne into the phone6s sili%on
An so on
Moreover, appli%ations running on a phone have to eal =ith the $a%t thatthey6re on a phone.
!eople =ith mobile phones ten to get very irritate =hen those phoneson6t =ork, =hi%h is =hy the Q%an you hear me no=Q a %ampaign $rom
+erion Wireless has been popular $or the past $e= years. #imilarly, thosesame people =ill get irritate at you i$ your program QbreaksQ their phone*
...by tying up the C!" su%h that %alls %an6t be re%eive
...by not =orking properly =ith the rest o$ the phone6s >#, su%h thatyour appli%ation oesn6t ;uietly $ae to the ba%kgroun =hen a %all
%omes in or nees to be pla%e
...by %rashing the phone6s operating system, su%h as by leakingmemory like a sieve
)en%e, eveloping programs $or a phone is a i$$erent e:perien%e thaneveloping esktop appli%ations, Web sites, or ba%ken server pro%esses.
@ou =in up =ith i$$erentlooking tools, i$$erentbehaving $rame=orks,an Qi$$erent than you6re use toQ limitations on =hat you %an o =ith yourprogram.
What Anroi tries to o is meet you hal$=ay*
@ou get a %ommonlyuse programming language &Gava' =ith some%ommonly use libraries &e.g., some Apa%he Commons A!-s', =ithsupport $or tools you may be use to &I%lipse'
%
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
25/400
The Big Picture
@ou get a $airly rigi an un%ommon $rame=ork in =hi%h yourprograms nee to run so they %an be Qgoo %itiensQ 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 avantage o$ its%apabilities.
What (ndroids (re +ade ,f
When you =rite a esktop appli%ation, you are Qmaster o$ your o=n
omainQ. @ou laun%h your main =ino= an any %hil =ino=s O like ialogbo:es O that are neee. (rom your stanpoint, you are your o=n =orl,leveraging $eatures supporte by the operating system, but largely ignoranto$ any other program that may be running on the %omputer at the sametime. -$ you o intera%t =ith other programs, it is typi%ally through an A!-,su%h as using GC &or $rame=orks atop it' to %ommuni%ate =ith My#HL oranother atabase.
Anroi has similar %on%epts, but pa%kage i$$erently, an stru%ture tomake phones more %rashresistant.
Activities
4he builing blo%k o$ the user inter$a%e is the activity. @ou %an think o$ ana%tivity as being the Anroi analogue $or the =ino= or ialog in a esktopappli%ation.
While it is possible $or a%tivities to not have a user inter$a%e, most likely your
QhealessQ %oe =ill be pa%kage in the $orm o$ %ontent proviers orservi%es, es%ribe belo=.
-
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
26/400
The Big Picture
Content Providers
Content proviers provie a level o$ abstra%tion $or any ata store on theevi%e that is a%%essible by multiple appli%ations. 4he Anroi evelopment
moel en%ourages you to make your o=n ata available to otherappli%ations, as =ell as your o=n O builing a %ontent provier lets you othat, =hile maintaining %omplete %ontrol over ho= your ata gets a%%esse.
Intents
-ntents are system messages, running aroun the insie o$ the evi%e,noti$ying appli%ations o$ various events, $rom har=are state %hanges &e.g.,
an # %ar =as inserte', to in%oming ata &e.g., an #M# message arrive',to appli%ation events &e.g., your a%tivity =as laun%he $rom the evi%e6smain menu'. /ot only %an you respon to intents, but you %an %reate youro=n, to laun%h other a%tivities, or to let you kno= =hen spe%i$i% situationsarise &e.g., raise su%hanso intent =hen the user gets =ithin 00 meters o$thisansu%h lo%ation'.
Services
A%tivities, %ontent proviers, an intent re%eivers are all shortlive an %anbe shut o=n at any time. #ervi%es, on the other han, are esigne to keeprunning, i$ neee, inepenent o$ any a%tivity. @ou might use a servi%e $or%he%king $or upates to an R## $ee, or to play ba%k musi% even i$ the%ontrolling a%tivity is no longer operating.
$
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
27/400
The Big Picture
Stuff (t .our /isposal
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 %arve out a small bit o$ spa%eon the evi%e itsel$, $or atabases or $iles %ontaining userentere orretrieve ata neee by your appli%ation. An, i$ the user supplies bulkstorage, like an # %ar, you %an rea an =rite $iles on there as neee.
"et#or$
Anroi evi%es =ill generally be -nternetreay, through one%ommuni%ations meium or another. @ou %an take avantage o$ the -nterneta%%ess at any level you =ish, $rom ra= Gava so%kets all the =ay up to a builtin
WebEitbase Web bro=ser =iget you %an embe in your appli%ation.
%ultimedi
Anroi evi%es have the ability to play ba%k an re%or auio an vieo.
While the spe%i$i%s may vary $rom evi%e to evi%e, you %an ;uery the evi%eto learn its %apabilities an then take avantage o$ the multimeia%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 auio notetaking.
GPS
Anroi evi%es =ill $re;uently have a%%ess to lo%ation proviers, su%h as7!#, that %an tell your appli%ations =here the evi%e is on the $a%e o$ the
Iarth. -n turn, you %an isplay maps or other=ise take avantage o$ thelo%ation ata, su%h as tra%king a evi%e6s movements i$ the evi%e has beenstolen.
0
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
28/400
The Big Picture
Phone Services
An, o$ %ourse, Anroi evi%es are typi%ally phones, allo=ing your so$t=areto initiate %alls, sen an re%eive #M# messages, an everything else you
e:pe%t $rom a moern bit o$ telephony te%hnology.
1
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
29/400
CHAPTER &
Pro2ect Structure
4he Anroi buil system is organie aroun a spe%i$i% ire%tory tree
stru%ture $or your Anroi proNe%t, mu%h like any other Gava proNe%t. 4hespe%i$i%s, though, are $airly uni;ue to Anroi an =hat it all oes toprepare the a%tual appli%ation that =ill run on the evi%e or emulator. )ere6sa ;ui%k primer on the proNe%t stru%ture, to help you make sense o$ it all,parti%ularly $or the sample %oe re$eren%e in this book.
3oot Contents
When you %reate a ne= Anroi proNe%t &e.g., via activitycreator', you get$ive key items in the proNe%t6s root ire%tory*
AndroidManifest.xml, =hi%h is an DML $ile es%ribing the appli%ationbeing built an =hat %omponents O a%tivities, servi%es, et%. O arebeing supplie by that appli%ation
build.xml, =hi%h is anAnts%ript $or %ompiling the appli%ation aninstalling it on the evi%e
bin/, =hi%h hols the appli%ation on%e it is %ompile
libs/, =hi%h hols any thirparty Gava GARs your appli%ationre;uires
src/, =hi%h hols the Gava sour%e %oe $or the appli%ation
res/, =hi%h hols Qresour%esQ, su%h as i%ons, 7"- layouts, an thelike, that get pa%kage =ith the %ompile Gava in the appli%ation
4
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
http://ant.apache.org/http://ant.apache.org/ -
8/13/2019 Android 1 2 CC
30/400
Pro2ect Structure
assets/, =hi%h hol other stati% $iles you =ish pa%kage =ith theappli%ation $or eployment onto the evi%e
The S)eat ,ff .our Bro)When you %reate the proNe%t &e.g., via activitycreator', you supplie the$ully;uali$ie %lass name o$ the QmainQ a%tivity $or the appli%ation &e.g.,com.commonsware.android.SomeDemo'. @ou =ill then $in that your proNe%t6ssrc/tree alreay has the namespa%e ire%tory tree in pla%e, plus a stubActivitysub%lass representing your main a%tivity &e.g., src/com/commonsware/android/SomeDemo.java'. @ou are =el%ome to moi$y this $ile an a othersto the src/tree as neee to implement your appli%ation.
4he $irst time you %ompile the proNe%t &e.g., via ant', out in the QmainQa%tivity6s namespa%e ire%tory, the Anroi buil %hain =ill %reate R.java.4his %ontains a number o$ %onstants tie to the various resour%es you pla%eout in the res/ire%tory tree. @ou shoul not moi$y R.javayoursel$, lettingthe Anroi tools hanle it $or you. @ou =ill see throughout many o$ thesamples =here =e re$eren%e things in R.java &e.g., re$erring to a layout6sienti$ier via R.layout.main'.
(nd 5o)6 The 3est of the Story
@ou =ill also $in that your proNe%t has a res/ire%tory tree. 4his holsQresour%esQ O stati% $iles that are pa%kage along =ith your appli%ation,either in their original $orm or, o%%asionally, in a prepro%esse $orm. #omeo$ the subire%tories you =ill $in or %reate uner res/in%lue*
res/drawable/$or images &!/7, G!I7, et%.'
res/layout/$or DMLbase "- layout spe%i$i%ations
res/raw/ $or generalpurpose $iles &e.g,. a C#+ $ile o$ a%%ountin$ormation'
res/values/$or strings, imensions, an the like
res/xml/$or other generalpurpose DML $iles you =ish to ship
7
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
31/400
Pro2ect Structure
We =ill %over all o$ these, an more, in later %hapters o$ this book.
What .ou 'et ,ut ,f 8t
When you %ompile your proNe%t &via antor the -I', the results go into thebin/ire%tory uner your proNe%t root. #pe%i$i%ally*
bin/classes/hols the %ompile Gava %lasses
bin/classes.dexhols the e:e%utable %reate $rom those %ompileGava %lasses
bin/yourapp.ap_ hols your appli%ation6s resour%es, pa%kage as a-! $ile &=here yourappis the name o$ your appli%ation'
bin/yourapp-debug.ap or bin/yourapp-unsigned.ap is the a%tualAnroi appli%ation &=here yourappis the name o$ your appli%ation'
4he .ap$ile is a -! ar%hive %ontaining the .dex$ile, the %ompile eition o$your resour%es &resources.arsc', any un%ompile resour%es &su%h as =hatyou put in res/raw/' an the AndroidManifest.xml $ile. -t is also igitallysigne, =ith the -debugportion o$ the $ilename ini%ating it has been signeusing a ebug key that =orks =ith the emulator, or -unsignedini%ating that
you built your appli%ation $or release &ant release', but the A!E still nees
to be signe using jarsigneran an o$$i%ial key.
9
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
32/400
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
33/400
CHAPTER
8nside the +anifest
4he $ounation $or any Anroi appli%ation is the mani$est $ile*
AndroidManifest.xmlin the root o$ your proNe%t. )ere is =here you e%lare=hat all is insie your appli%ation O the a%tivities, the servi%es, an so on.@ou also ini%ate ho= these pie%es atta%h themselves to the overall AnroisystemP $or e:ample, you ini%ate =hi%h a%tivity &or a%tivities' shoul appearon the evi%e6s main menu &a.k.a., laun%her'.
When you %reate your appli%ation, you =ill get a starter mani$est generate$or you. (or a simple appli%ation, o$$ering a single a%tivity an nothing else,the autogenerate mani$est =ill probably =ork out $ine, or perhaps re;uire
a $e= minor moi$i%ations. >n the other en o$ the spe%trum, the mani$est$ile $or the Anroi A!- emo suite is over ,000 lines long. @our prou%tion
Anroi appli%ations =ill probably $all some=here in the mile.
Most o$ the interesting bits o$ the mani$est =ill be es%ribe in greateretail in the %hapters on their asso%iate Anroi $eatures. (or e:ample, theserviceelement =ill be es%ribe in greater etail in the %hapter on %reatingservi%es. (or no=, =e Nust nee to unerstan =hat the role o$ the mani$estis an its general overall %onstru%tion.
8n The Beginning6 There Was the 3oot6 (nd 8tWas 'ood
4he root o$ all mani$est $iles is, not surprisingly, a manifestelement*
**
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
34/400
8nside the +anifest
"manifest xmlns#android$%&ttp#//sc&emas.android.com/ap/res/android% pacage$%com.commonsware.android.searc&%'..."/manifest'
/ote the namespa%e e%laration. Curiously, the generate mani$ests onlyapply it on the attributes, not the elements &e.g., it6s manifest, notandroid#manifest'. )o=ever, that pattern =orks, so unless Anroi %hanges,sti%k =ith their pattern.
4he biggest pie%e o$ in$ormation you nee to supply on the manifestelement is the pacageattribute &also %uriously notnamespa%e'. )ere, you%an provie the name o$ the Gava pa%kage that =ill be %onsiere the QbaseQo$ your appli%ation. 4hen, every=here else in the mani$est $ile that nees a
%lass name, you %an Nust substitute a leaing ot as shorthan $or thepa%kage. (or e:ample, i$ you neee to re$er tocom.commonsware.android.Sniclefrit( in this mani$est sho=n above, you%oul Nust use .Sniclefrit(, sin%e com.commonsware.androidis e$ine as theappli%ation6s pa%kage.
Permissions6 8nstrumentations6 and (pplica"tions #,h6 +y!&
"nerneath the manifestelement, you =ill $in*
uses-permission elements, to ini%ate =hat permissions yourappli%ation =ill nee in orer to $un%tion properly O see the %hapteron permissions$or more etails
permission elements, to e%lare permissions that a%tivities orservi%es might re;uire other appli%ations hol in orer to use yourappli%ation6s ata or logi% O again, more etails are $orth%oming inthe %hapter on permissions
instrumentationelements, to ini%ate %oe that shoul be invokeon key system events, su%h as starting up a%tivities, $or the purposeso$ logging or monitoring
uses-library elements, to hook in optional Anroi %omponents,su%h as mapping servi%es
*%
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
35/400
8nside the +anifest
an applicationelement, e$ining the guts o$ the appli%ation that themani$est es%ribes
"manifest xmlns#android$%&ttp#//sc&emas.android.com/ap/res/android% pacage$%com.commonsware.android%'
"uses-permission android#name$%android.permission.A))*SS_+,)A,% /' "uses-permission android#name$%android.permission.A))*SS_01S% /'
"uses-permission android#name$%android.permission.A))*SS_ASSS*D_01S% /'
"uses-permission android#name$%android.permission.A))*SS_)*++_D% /'
"application'... "/application'"/manifest'
-n the pre%eing e:ample, the mani$est has uses-permission elements toini%ate some evi%e %apabilities the appli%ation =ill nee O in this %ase,permissions to allo= the appli%ation to etermine its %urrent lo%ation. An,there is the applicationelement, =hose %ontents =ill es%ribe the a%tivities,servi%es, an =hatnot that make up the bulk o$ the appli%ation itsel$.
.our (pplication /oes Something6 3ight:
4he real meat o$ the mani$est $ile are the %hilren o$ the applicationelement.
y e$ault, =hen you %reate a ne= Anroi proNe%t, you get a single activityelement*
"manifest xmlns#android$%&ttp#//sc&emas.android.com/ap/res/android% pacage$%com.commonsware.android.seleton%' "application' "activity android#name$%.ow% android#label$%ow%' "intent-filter' "action android#name$%android.intent.action.MA% /' "category android#name$%android.intent.category.+A2)3*R% /' "/intent-filter' "/activity' "/application'"/manifest'
*-
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
36/400
8nside the +anifest
4his element supplies android#name$or the %lass implementing the a%tivity,android#label $or the isplay name o$ the a%tivity, an &$re;uently' anintent-filter%hil element es%ribing uner =hat %onitions this a%tivity
=ill be isplaye. 4he sto%k activityelement sets up your a%tivity to appear
in the laun%her, so users %an %hoose to run it. As =e6ll see later in this book,you %an have several a%tivities in one proNe%t, i$ you so %hoose.
@ou may also have one or more receiverelements, ini%ating nona%tivitiesthat shoul be triggere uner %ertain %onitions, su%h as =hen an #M#message %omes in. 4hese are %alle intent re%eivers an are es%ribe mi
=ay through the book.
@ou may have one or more providerelements, ini%ating %ontent proviers O
%omponents that supply ata to your a%tivities an, =ith your permission,other a%tivities in other appli%ations on the evi%e. 4hese =rap up atabasesor other ata stores into a single A!- that any appli%ation %an use. Later,
=e6ll see ho= to%reate %ontent proviersan ho= to use %ontent proviersthat you or others %reate.
(inally, you may have one or more serviceelements, es%ribing servi%es Olongrunning pie%es o$ %oe that %an operate inepenent o$ any a%tivity.4he ;uintessential e:ample is the M!? player, =here you =ant the musi% to
keep playing even i$ the user pops open other a%tivities an the M!? player6suser inter$a%e is Qmispla%eQ. 4=o %hapters late in the book %over ho= to%reatean use servi%es.
*$
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
37/400
PART II Activities
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
38/400
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
39/400
CHAPTER (
Creating a Skeleton (pplication
Ivery programming language or environment book starts o$$ =ith the ever
popular Q)ello, Worl9Q emonstration* Nust enough o$ a program to proveyou %an buil things, not so mu%h that you %annot unerstan =hat is goingon. )o=ever, the typi%al Q)ello, Worl9Q program has no intera%tivity &e.g.,
Nust umps the =ors to a %onsole', an so is really boring.
4his %hapter emonstrates a simple proNe%t, but one using Avan%e !ushutton 4e%hnology an the %urrent time, to sho= you ho= a simple
Anroi a%tivity =orks.
Begin at the Beginning
4o =ork =ith anything in Anroi, you nee a proNe%t. With orinary Gava, i$you =ante, you %oul Nust =rite a program as a single $ile, %ompile it =ithjavac, an run it =ith java, =ithout any other support stru%tures. Anroi ismore %omple:, but to help keep it manageable, 7oogle has supplie tools tohelp %reate the proNe%t. -$ you are using an Anroienable -I, su%h asI%lipse =ith the Anroi plugin, you %an %reate a proNe%t insie o$ the -I
&e.g., sele%t 2ile @ >e0 @ Pro"ect, then %hoose Android @ AndroidPro"ect'.
-$ you are using tools that are not Anroienable, you %an use theactivitycreator s%ript, $oun in the tools/ ire%tory in your #Einstallation. Gust pass activitycreatorthe pa%kage name o$ the a%tivity you
*4
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
40/400
Creating a Skeleton (pplication
=ant to %reate an a --outs=it%h ini%ating =here the proNe%t $iles shoulbe generate. (or e:ample*
activitycreator --out /pat&/to/my/project/dir 4com.commonsware.android.ow
@ou =ill =in up =ith a han$ul o$ pregenerate $iles, as es%ribe in aprevious %hapter.
(or the purposes o$ the samples sho=n in this book, you %an o=nloa theirproNe%t ire%tories in a -! $ile on the CommonsWare Web site. 4heseproNe%ts are reay $or useP you o not nee to run activitycreatoron thoseunpa%ke samples.
The (ctivity
@our proNe%t6s src/ ire%tory %ontains the stanar Gavastyle tree o$ire%tories base upon the Gava pa%kage you %hose =hen you %reate theproNe%t &e.g., com.commonsware.android results insrc/com/commonsware/android/'. -nsie the innermost ire%tory you shoul$in a pregenerate sour%e $ile name ow.java, =hi%h =here your $irsta%tivity =ill go.
>pen ow.javain your eitor an paste in the $ollo=ing %oe*
pacagecom.commonsware.android.seleton5
importandroid.app.Activity5importandroid.os.6undle5importandroid.view.7iew5importandroid.widget.6utton5importjava.util.Date5
publicclassow extendsActivity implements7iew.,n)lic+istener 8 6utton btn5
9,verride publicvoidonCreate:6undle icicle;8 super.onCreate:icicle;5
btn $newButton:t&is;5 btn.setOnClickListener:t&is;5
*7
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
41/400
Creating a Skeleton (pplication
updateTime:;5 setContentView:btn;5 pen that appli%ation
@ou shoul see an a%tivity s%reen akin to*
igure -< The 5o) demonstration activity
%%
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
45/400
Creating a Skeleton (pplication
Cli%king the button O in other =ors, pretty mu%h any=here on the phone6ss%reen O =ill upate the time sho=n in the button6s label.
/ote that the label is %entere horiontally an verti%ally, as those are the
e$ault styles applie to button %aptions. We %an %ontrol that $ormatting,=hi%h =ill be %overe in a later %hapter.
A$ter you are one gaing at the a=esomeness o$ Avan%e !ushutton4e%hnology, you %an %li%k the ba%k button on the emulator to return to thelaun%her.
%-
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
46/400
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
47/400
CHAPTER )
>sing ?+"Based ayouts
While it is te%hni%ally possible to %reate an atta%h =igets to our a%tivity
purely through Gava %oe, the =ay =e i in the pre%eing %hapter,the more%ommon approa%h is to use an DMLbase layout $ile. ynami%instantiation o$ =igets is reserve $or more %ompli%ate s%enarios, =herethe =igets are not kno=n at %ompiletime &e.g., populating a %olumn o$raio buttons base on ata retrieve o$$ the -nternet'.
With that in min, it6s time to break out the DML an learn out to lay outAnroi a%tivity vie=s that =ay.
What 8s an ?+"Based ayout:
As the name suggests, an DMLbase layout is a spe%i$i%ation o$ =igets6relationships to ea%h other O an to %ontainers O en%oe in DML $ormat.#pe%i$i%ally, Anroi %onsiers DMLbase layouts to be resour%es, an assu%h layout $iles are store in the res/layoutire%tory insie your AnroiproNe%t.
Ia%h DML $ile %ontains a tree o$ elements spe%i$ying a layout o$ =igets an%ontainers that make up one 7iew. 4he attributes o$ the DML elements areproperties, es%ribing ho= a =iget shoul look or ho= a %ontainer shoulbehave. (or e:ample, i$ a 6utton element has an attribute value o$android#textStyle $ %bold%, that means that the te:t appearing on the $a%eo$ the button shoul be renere in a bol$a%e $ont style.
%0
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
48/400
>sing ?+"Based ayouts
Anroi6s #E ships =ith a tool &aapt' =hi%h uses the layouts. 4his toolshoul be automati%ally invoke by your Anroi tool %hain &e.g., I%lipse,
Ant6s build.xml'. >$ parti%ular importan%e to you as a eveloper is that aaptgenerates the R.javasour%e $ile =ithin your proNe%t, allo=ing you to a%%ess
layouts an =igets =ithin those layouts ire%tly $rom your Gava %oe, as =illbe emonstrate .
Why >se ?+"Based ayouts:
Most everything you o using DML layout $iles %an be a%hieve through Gava%oe. (or e:ample, you %oul use setypeface:;to have a button rener itste:t in bol, instea o$ using a property in an DML layout. #in%e DMLlayouts are yet another $ile $or you to keep tra%k o$, =e nee goo reasons $orusing su%h $iles.
!erhaps the biggest reason is to assist in the %reation o$ tools $or vie=e$inition, su%h as a 7"- builer in an -I like I%lipse or a ei%ate
Anroi 7"- esigner like roira=. #u%h 7"- builers %oul, inprin%iple, generate Gava %oe instea o$ DML. 4he %hallenge is rereaingthe e$inition in to support eits O that is $ar simpler i$ the ata is in astru%ture $ormat like DML than in a programming language. Moreover,keeping the generate bits separate out $rom han=ritten %oe makes itless likely that someboy6s %ustom%ra$te sour%e =ill get %lobbere bya%%ient =hen the generate bits get regenerate. DML $orms a ni%e milegroun bet=een something that is easy $or tool=riters to use an easy $orprogrammers to =ork =ith by han as neee.
Also, DML as a 7"- e$inition $ormat is be%oming more %ommonpla%e.Mi%roso$t6s DAML, Aobe6s (le:, an Moilla6s D"L all take a similarapproa%h to that o$ Anroi* put layout etails in an DML $ile an putprogramming smarts in sour%e $iles &e.g., Gavas%ript $or D"L'. Many less
=ellkno=n 7"- $rame=orks, su%h as E, also use DML $or vie= e$inition.While Q$ollo=ing the herQ is not ne%essarily the best poli%y, it oes have theavantage o$ helping to ease the transition into Anroi $rom any other
DML%entere vie= es%ription language.
%1
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
http://droiddraw.org/http://droiddraw.org/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.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/13/2019 Android 1 2 CC
49/400
>sing ?+"Based ayouts
,@6 So What /oes 8t ook ike:
)ere is the 6utton$rom the previous %hapter6s sample appli%ation, %onverteinto an DML layout $ile*
">xml version$%?.@% encoding$%utf-%>'"6utton xmlns#android$%&ttp#//sc&emas.android.com/ap/res/android% android#id$%9Bid/button% android#text$%% android#layout_widt&$%fill_parent% android#layout_&eig&t$%fill_parent%/'
4he %lass name o$ the =iget O 6utton O $orms the name o$ the DMLelement. #in%e 6uttonis an Anroisupplie =iget, =e %an Nust use thebare %lass name. -$ you %reate your o=n =igets as sub%lasses o$android.view.7iew, you =oul nee to provie a $ull pa%kage e%laration as
=ell &e.g., com.commonsware.android.MyCidget'.
4he root element nees to e%lare the Anroi DML namespa%e*
xmlns#android$%&ttp#//sc&emas.android.com/ap/res/android%
All other elements =ill be %hilren o$ the root an =ill inherit thatnamespa%e e%laration.
e%ause =e =ant to re$eren%e this button $rom our Gava %oe, =e nee to giveit an ienti$ier via the android#idattribute. We =ill %over this %on%ept ingreater etail .
4he remaining attributes are properties o$ this 6uttoninstan%e*
android#textini%ates the initial te:t to be isplaye on the button$a%e &in this %ase, an empty string'
android#layout_widt&an android#layout_&eig&ttell Anroi to havethe button6s =ith an height $ill the QparentQ, in this %ase the entires%reen O these attributes =ill be %overe in greater etail in a later%hapter
%4
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
50/400
>sing ?+"Based ayouts
#in%e this single =iget is the only %ontent in our a%tivity6s vie=, =e onlynee this single element. Comple: vie=s =ill re;uire a =hole tree o$elements, representing the =igets an %ontainers that %ontrol theirpositioning. All the remaining %hapters o$ this book =ill use the DML layout
$orm =henever pra%ti%al, so there are oens o$ other e:amples o$ more%omple: layouts $or you to peruse.
WhatAs With the Signs:
Many =igets an %ontainers only nee to appear in the DML layout $ile ano not nee to be re$eren%e in your Gava %oe. (or e:ample, a stati% label&ext7iew' $re;uently only nees to be in the layout $ile to ini%ate =here itshoul appear. 4hese sorts o$ elements in the DML $ile o not nee to havethe android#idattribute to give them a name.
Anything you do =ant to use in your Gava sour%e, though, nees anandroid#id.
4he %onvention is to use 9Bid/...as the idvalue, =here the ...representsyour lo%allyuni;ue name $or the =iget in ;uestion. -n the DML layoute:ample in the pre%eing se%tion, 9Bid/buttonis the ienti$ier $or the 6utton
=iget.
Anroi provies a $e= spe%ial android#id values, o$ the $orm9android#id/...O =e =ill see some o$ these in various %hapters o$ this book.
(nd We (ttach These to the ava
-
8/13/2019 Android 1 2 CC
51/400
>sing ?+"Based ayouts
4his is the same set)ontent7iew:;=e use earlier, passing it an instan%e o$ a7iewsub%lass &in that %ase, a 6utton'. 4he Anroibuilt 7iew, %onstru%te$rom our layout, is a%%esse $rom that %oegenerate R%lass. All o$ thelayouts are a%%essible uner R.layout, keye by the base name o$ the layout
$ile O main.xmlresults in R.layout.main.
4o a%%ess our ienti$ie =igets, use find7iew6yd:;, passing it the numeri%ienti$ier o$ the =iget in ;uestion. 4hat numeri% ienti$ier =as generateby Anroi in the R%lass as R.id.somet&ing&=here somet&ingis the spe%i$i%
=iget you are seeking'. 4hose =igets are simply sub%lasses o$ 7iew, Nustlike the 6uttoninstan%e =e %reate in the previous %hapter.
The 3est of the Story-n the original owemo, the button6s $a%e =oul sho= the %urrent time,
=hi%h =oul re$le%t =hen the button =as last pushe &or =hen the a%tivity=as $irst sho=n, i$ the button ha not yet been pushe'.
Most o$ that logi% still =orks, even in this revise emo &owRedux'. )o=ever,rather than instantiating the 6uttonin our a%tivity6s on)reate:;%allba%k, =e%an re$eren%e the one $rom the DML layout*
pacagecom.commonsware.android.layouts5
importandroid.app.Activity5importandroid.os.6undle5importandroid.view.7iew5importandroid.widget.6utton5importjava.util.Date5
publicclassowRedux extendsActivity implements7iew.,n)lic+istener 8 6utton btn5
9,verride publicvoidonCreate:6undle icicle;8 super.onCreate:icicle;5
setContentView:R.layout.main;5
btn$:6utton;findViewById:R.id.button;5 btn.setOnClickListener:t&is;5 updateTime:;5
%9
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
52/400
>sing ?+"Based ayouts
xml version$%?.@% encoding$%utf-%>'"ext7iew xmlns#android$%&ttp#//sc&emas.android.com/ap/res/android% android#layout_widt&$%fill_parent%
android#layout_&eig&t$%wrap_content%android#text$%Fou were expecting somet&ing profound>%
/'
Gust that layout alone, =ith the stub Gava sour%e provie by Anroi6sproNe%t builer &e.g., activity)reator', gives you*
igure 0< The abel/emo sample application
Button6 Button6 WhoAs 'ot the Button:
We6ve alreay seen the use o$ the 6utton =iget in the previous t=o%hapters. As it turns out, 6utton is a sub%lass o$ ext7iew, so everythingis%usse in the pre%eing se%tion in terms o$ $ormatting the $a%e o$ thebutton still hols.
-$
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
57/400
Employing Basic Widgets
leeting 8mages
Anroi has t=o =igets to help you embe images in your a%tivities*mage7iew an mage6utton. As the names suggest, they are imagebase
analogues to ext7iewan 6utton, respe%tively.
Ia%h =iget takes an android#srcattribute &in an DML layout' to spe%i$y=hat pi%ture to use. 4hese usually re$eren%e a ra=able resour%e, es%ribein greater etail in the %hapter on resour%es.@ou %an also set the image%ontent base on a 2ri$rom a %ontent proviervia setmage2R:;.
mage6utton, a sub%lass o$ mage7iew, mi:es in the stanar 6uttonbehaviors,$or responing to %li%ks an =hatnot.
(or e:ample, take a peek at the main.xmllayout $rom the mage7iewsampleproNe%t*
">xml version$%?.@% encoding$%utf-%>'"mage7iew xmlns#android$%&ttp#//sc&emas.android.com/ap/res/android% android#id$%9Bid/icon% android#layout_widt&$%fill_parent%
android#layout_&eig&t$%fill_parent% android#adjust7iew6ounds$%true% android#src$%9drawable/molecule% /'
4he result, Nust using the %oegenerate a%tivity, is simply the image*
-0
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
58/400
Employing Basic Widgets
igure 1< The 8mageFie)/emo sample application
ields of 'reen< ,r ,ther Colorsxml version$%?.@% encoding$%utf-%>'"*ditext xmlns#android$%&ttp#//sc&emas.android.com/ap/res/android% android#id$%9Bid/field%
android#layout_widt&$%fill_parent%android#layout_&eig&t$%fill_parent%
android#single+ine$%false% /'
/ote that android#single+ineis $alse, so users =ill be able to enter in severallines o$ te:t.
(or this proNe%t, the EieldDemo.java$ile populates the input $iel =ith someprose*
pacagecom.commonsware.android.basic5
importandroid.app.Activity5importandroid.os.6undle5importandroid.widget.*ditext5
publicclassEieldDemo extendsActivity 8 9,verride publicvoidonCreate:6undle icicle;8 super.onCreate:icicle;5 setContentView:R.layout.main;5
*ditext fld$:*ditext;findViewById:R.id.field;5 fld.setText:%+icensed under t&e Apac&e +icenseG 7ersion H.@ %B %:t&e 4%+icense4%;5 you may not use t&is file %B %except in compliance wit& t&e +icense. Fou may %B %obtain a copy of t&e +icense at %B %&ttp#//www.apac&e.org/licenses/+)*S*-H.@% ;5 xml version$%?.@% encoding$%utf-%>'"Radio0roup xmlns#android$%&ttp#//sc&emas.android.com/ap/res/android% android#orientation$%vertical%
android#layout_widt&$%fill_parent% android#layout_&eig&t$%fill_parent% ' "Radio6utton android#id$%9Bid/radio?% android#layout_widt&$%wrap_content% android#layout_&eig&t$%wrap_content% android#text$%Roc% /'
$%
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
65/400
Employing Basic Widgets
"Radio6utton android#id$%9Bid/radioH% android#layout_widt&$%wrap_content% android#layout_&eig&t$%wrap_content% android#text$%Scissors% /'
"Radio6utton android#id$%9Bid/radioI%
android#layout_widt&$%wrap_content% android#layout_&eig&t$%wrap_content% android#text$%1aper% /'"/Radio0roup'
"sing the sto%k Anroigenerate Gava $or the proNe%t an this layout, youget*
igure *;< The 3adioButton/emo sample application
/ote that the raio button group is initially set to be %ompletely un%he%keat the outset. 4o preset one o$ the raio buttons to be %he%ke, use eitherset)&eced:;on the Radio6utton or c&ec:;on the Radio0roup$rom =ithin
your on)reate:;%allba%k in your a%tivity.
$-
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
66/400
Employing Basic Widgets
8tAs Guite a Fie)
All =igets, in%luing the ones sho=n above, e:ten 7iew, an as su%h giveall =igets an array o$ use$ul properties an methos beyon those alreay
es%ribe.
+se,ul Properties
#ome o$ the properties on 7iewmost likely to be use in%lue*
Controls the $o%us se;uen%e*
android#nextEocusDown
android#nextEocus+eft
android#nextEocusRig&t
android#nextEocus2p
android#visibility, =hi%h %ontrols =hether the =iget is initiallyvisible
android#bacground, =hi%h typi%ally provies an R7 %olor value&e.g., @@EE@@$or green' to serve as the ba%kgroun $or the =iget
+se,ul %ethods
@ou %an toggle =hether or not a =iget is enable via set*nabled:;an see i$it is enable via is*nabled:;. >ne %ommon use pattern $or this is to isablesome =igets base on a )&ec6oxor Radio6uttonsele%tion.
@ou %an give a =iget $o%us via reJuestEocus:;an see i$ it is $o%use viaisEocused:;. @ou might use this in %on%ert =ith isabling =igets as
mentione above, to ensure the proper =iget has the $o%us on%e yourisabling operation is %omplete.
4o help navigate the tree o$ =igets an %ontainers that make up ana%tivity6s overall vie=, you %an use*
$$
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
67/400
Employing Basic Widgets
get1arent:;to $in the parent =iget or %ontainer
find7iew6yd:;to $in a %hil =iget =ith a %ertain -
getRoot7iew:;to get the root o$ the tree &e.g., =hat you provie to
the a%tivity via set)ontent7iew:;'
$0
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
68/400
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
69/400
CHAPTER -
Working )ith Containers
Containers pour a %olle%tion o$ =igets &an possibly %hil %ontainers' into
spe%i$i% layouts you like. -$ you =ant a $orm =ith labels on the le$t an $ielson the right, you =ill nee a %ontainer. -$ you =ant >E an Can%el buttonsto be beneath the rest o$ the $orm, ne:t to one another, an $lush to rightsie o$ the s%reen, you =ill nee a %ontainer. Gust $rom a pure DMLperspe%tive, i$ you have multiple =igets &beyon Radio6utton=igets in aRadio0roup', you =ill nee a %ontainer Nust to have a root element to pla%ethe =igets insie.
Most 7"- toolkits have some notion o$ layout management, $re;uently
organie into %ontainers. -n GavaU#=ing, $or e:ample, you have layoutmanagers like 6ox+ayout an %ontainers that use them &e.g., 6ox'. #ometoolkits sti%k stri%tly to the bo: moel, su%h as D"L an (le:, $iguring thatany esire layout %an be a%hieve through the right %ombination o$ nestebo:es.
Anroi, through +inear+ayout, also o$$ers a Qbo:Q moel, but in aitionsupports a range o$ %ontainers proviing i$$erent layout rules. -n this%hapter, =e =ill look at three %ommonlyuse %ontainers* +inear+ayout&the
bo: moel', Relative+ayout&a rulebase moel', an able+ayout&the grimoel', along =ith Scroll7iew, a %ontainer esigne to assist =ithimplementing s%rolling %ontainers. -n the ne:t %hapter, =e =ill e:aminesome more esoteri% %ontainers.
$4
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
70/400
Working )ith Containers
Thinking inearly
As note above, +inear+ayoutis a bo: moel O =igets or %hil %ontainersare line up in a %olumn or ro=, one a$ter the ne:t. 4his =orks similar toElow+ayoutin GavaU#=ing, vboxan &boxin (le: an D"L, et%.
(le: an D"L use the bo: as their primary unit o$ layout. -$ you =ant, you%an use +inear+ayoutin mu%h the same =ay, es%he=ing some o$ the other%ontainers. 7etting the visual representation you =ant is mostly a matter o$ienti$ying =here bo:es shoul nest an =hat properties those bo:es shoulhave, su%h as alignment vis a vis other bo:es.
Concepts nd Properties
4o %on$igure a +inear+ayout, you have $ive main areas o$ %ontrol besies the%ontainer6s %ontents* the orientation, the $ill moel, the =eight, the gravity,an the paing.
Orientation
>rientation ini%ates =hether the +inear+ayout represents a ro= or a%olumn. Gust a the android#orientation property to your +inear+ayoutelement in your DML layout, setting the value to be &ori(ontal$or a ro= orvertical$or a %olumn.
4he orientation %an be moi$ie at runtime by invoking set,rientation:;onthe +inear+ayout, supplying it either 3,RK,A+or 7*R)A+.
Fill Model
Let6s imagine a ro= o$ =igets, su%h as a pair o$ raio buttons. 4hese =igetshave a QnaturalQ sie base on their te:t. 4heir %ombine sies probably onot e:a%tly mat%h the =ith o$ the Anroi evi%e6s s%reen O parti%ularlysin%e s%reens %ome in various sies. We then have the issue o$ =hat to o
=ith the remaining spa%e.
$7
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
71/400
Working )ith Containers
All =igets insie a +inear+ayout must supply android#layout_widt& anandroid#layout_&eig&t properties to help aress this issue. 4heseproperties6 values have three $lavors*
@ou %an provie a spe%i$i% imension, su%h as?HLpx
to ini%ate the=iget shoul take up e:a%tly 2B pi:els
@ou %an provie wrap_content, =hi%h means the =iget shoul $ill upits natural spa%e, unless that is too big, in =hi%h %ase Anroi %anuse =or=rap as neee to make it $it
@ou %an provie fill_parent, =hi%h means the =iget shoul $ill upall available spa%e in its en%losing %ontainer, a$ter all other =igetsare taken %are o$
4he latter t=o $lavors are the most %ommon, as they are inepenent o$s%reen sie, allo=ing Anroi to aNust your vie= to $it the available spa%e.
Weight
ut, =hat happens i$ =e have t=o =igets that shoul split the available $reespa%e (or e:ample, suppose =e have t=o multiline $iels in a %olumn, an
=e =ant them to take up the remaining spa%e in the %olumn a$ter all other
=igets have been allo%ate their spa%e.
4o make this =ork, in aition to setting android#layout_widt&&$or ro=s' orandroid#layout_&eig&t &$or %olumns' to fill_parent, you must also setandroid#layout_weig&t. 4his property ini%ates =hat proportion o$ the $reespa%e shoul go to that =iget. -$ you set android#layout_weig&tto be thesame value $or a pair o$ =igets &e.g., ?', the $ree spa%e =ill be split evenlybet=een them. -$ you set it to be ?$or one =iget an H$or another =iget,the se%on =iget =ill use up t=i%e the $ree spa%e that the $irst =iget oes.
An so on.
$9
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
72/400
Working )ith Containers
Gravity
y e$ault, everything is le$t an topaligne. #o, i$ you %reate a ro= o$=igets via a horiontal +inear+ayout, the ro= =ill start $lush on the le$t sie
o$ the s%reen.
-$ that is not =hat you =ant, you nee to spe%i$y a gravity. "singandroid#layout_gravity on a =iget &or %alling set0ravity:;at runtime onthe =iget6s Gava obNe%t', you %an tell the =iget an its %ontainer ho= toalign it vis a vis the s%reen.
(or a %olumn o$ =igets, %ommon gravity values are left, center_&ori(ontal,an rig&t$or le$taligne, %entere, an rightaligne =igets respe%tively.
(or a ro= o$ =igets, the e$ault is $or them to be aligne so their te:ts arealigne on the baseline &the invisible line that letters seem to Qsit onQ',though you may =ish to spe%i$y a gravity o$ center_verticalto %enter the
=igets along the ro=6s verti%al mipoint.
Padding
y e$ault, =igets are tightly pa%ke ne:t to ea%h other. -$ you =ant toin%rease the =hitespa%e bet=een =igets, you =ill =ant to use theandroid#padding property &or by %alling set1adding:; at runtime on the
=iget6s Gava obNe%t'.
4he paing spe%i$ies ho= mu%h spa%e there is bet=een the bounaries o$the =iget6s Q%ellQ an the a%tual =iget %ontents. !aing is analogous tothe margins on a =or pro%essing o%ument O the page sie might be8.BQ:Q, but Q margins =oul leave the a%tual te:t to resie =ithin a 3.BQ:Q
area.
0;
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
73/400
Working )ith Containers
igure **< The relationship bet)een a )idget6 its cell6 and the padding values
4he android#paddingproperty allo=s you to set the same paing on all $our
sies o$ the =iget, =ith the =iget6s %ontents itsel$ %entere =ithin thatpaeout area. -$ you =ant the paing to i$$er on i$$erent sies, useandroid#padding+eft, android#paddingRig&t, android#paddingop, anandroid#padding6ottom.
4he value o$ the paing is a imension, su%h as Lpx$or B pi:els6 =orth o$paing.
E.mple
Let6s look at an e:ample &+inear' that sho=s +inear+ayout properties setboth in the DML layout $ile an at runtime.
)ere is the layout*
0*
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
74/400
Working )ith Containers
">xml version$%?.@% encoding$%utf-%>'"+inear+ayout xmlns#android$%&ttp#//sc&emas.android.com/ap/res/android% android#orientation$%vertical% android#layout_widt&$%fill_parent% android#layout_&eig&t$%fill_parent%
' "Radio0roup android#id$%9Bid/orientation% android#orientation$%&ori(ontal% android#layout_widt&$%wrap_content% android#layout_&eig&t$%wrap_content% android#padding$%Lpx%' "Radio6utton android#id$%9Bid/&ori(ontal% android#text$%&ori(ontal% /' "Radio6utton android#id$%9Bid/vertical% android#text$%vertical% /' "/Radio0roup'
"Radio0roup android#id$%9Bid/gravity% android#orientation$%vertical% android#layout_widt&$%fill_parent% android#layout_&eig&t$%wrap_content% android#padding$%Lpx%' "Radio6utton android#id$%9Bid/left% android#text$%left% /' "Radio6utton android#id$%9Bid/center% android#text$%center% /' "Radio6utton android#id$%9Bid/rig&t% android#text$%rig&t% /'
"/Radio0roup'"/+inear+ayout'
/ote that =e have a +inear+ayout=rapping t=o Radio0roupsets. Radio0roupisa sub%lass o$ +inear+ayout, so our e:ample emonstrates neste bo:es as i$they =ere all +inear+ayout%ontainers.
4he top Radio0roupsets up a ro= &android#orientation $ %&ori(ontal%' o$Radio6utton =igets. 4he Radio0roup has Lpx o$ paing on all sies,
separating it $rom the other Radio0roup. 4he =ith an height are both set towrap_content, so the raio buttons =ill only take up the spa%e that they nee.
4he bottom Radio0roupis a %olumn &android#orientation $ %vertical%' o$three Radio6utton=igets. Again, =e have Lpxo$ paing on all sies an aQnaturalQ height &android#layout_&eig&t $ %wrap_content%'. )o=ever, =e
0%
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
75/400
Working )ith Containers
have set android#layout_widt& to be fill_parent, meaning the %olumn o$raio buttons Q%laimsQ the entire =ith o$ the s%reen.
4o aNust these settings at runtime base on user input, =e nee some Gava
%oe*
pacagecom.commonsware.android.containers5
importandroid.app.Activity5importandroid.os.6undle5importandroid.text.extCatc&er5importandroid.widget.+inear+ayout5importandroid.widget.Radio0roup5importandroid.widget.*ditext5
publicclass+inear+ayoutDemo extendsActivity
implementsRadio0roup.,n)&eced)&ange+istener 8 Radio0roup orientation5 Radio0roup gravity5
9,verride publicvoidonCreate:6undle icicle;8 super.onCreate:icicle;5 setContentView:R.layout.main;5
orientation$:Radio0roup;findViewById:R.id.orientation;5 orientation.setOnCheckedChangeListener:t&is;5 gravity$:Radio0roup;findViewById:R.id.gravity;5 gravity.setOnCheckedChangeListener:t&is;5 Ebutton &android#layout_alignop $ %9id/o%'.
With no %hanges to the autogenerate Gava %oe, the emulator gives us*
1*
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
84/400
Working )ith Containers
igure *1< The 3elativeayout/emo sample application
Tabula 3asa
-$ you like )4ML tables, spreasheet gris, an the like, you =ill likeAnroi6s able+ayoutO it allo=s you to position your =igets in a gri to
your spe%i$i%ations. @ou %ontrol the number o$ ro=s an %olumns, =hi%h%olumns might shrink or stret%h to a%%ommoate their %ontents, an so on.
able+ayout =orks in %onNun%tion =ith ableRow. able+ayout %ontrols theoverall behavior o$ the %ontainer, =ith the =igets themselves poure intoone or more ableRow%ontainers, one per ro= in the gri.
Concepts nd Properties
(or all this to =ork, =e nee to $igure out ho= =igets =ork =ith ro=s an%olumns, plus ho= to hanle =igets that live outsie o$ ro=s.
1%
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
85/400
Working )ith Containers
Putting Cells in Rows
Ro=s are e%lare by you, the eveloper, by putting =igets as %hilren o$ aableRowinsie the overall able+ayout. @ou, there$ore, %ontrol ire%tly ho=
many ro=s appear in the table.
4he number o$ %olumns are etermine by AnroiP you %ontrol thenumber o$ %olumns in an inire%t $ashion.
(irst, there =ill be at least one %olumn per =iget in your longest ro=. #o i$you have three ro=s, one =ith t=o =igets, one =ith three =igets, an one=ith $our =igets, there =ill be at least $our %olumns.
)o=ever, a =iget %an take up more than one %olumn by in%luing theandroid#layout_spanproperty, ini%ating the number o$ %olumns the =igetspans. 4his is akin to the colspanattribute one $ins in table %ells in )4ML*
"ableRow' "ext7iew android#text$%2R+#% /' "*ditext android#id$%9Bid/entry% android#layout_span$%I%/'"/ableRow'
-n the above DML layout $ragment, the $iel spans three %olumns.
>rinarily, =igets are put into the $irst available %olumn. -n the above$ragment, the label =oul go in the $irst %olumn &%olumn @, as %olumns are%ounte starting $rom @', an the $iel =oul go into a spanne set o$ three%olumns &%olumns ? through I'. )o=ever, you %an put a =iget into ai$$erent %olumn via the android#layout_columnproperty, spe%i$ying the @base %olumn the =iget belongs to*
"ableRow' "6utton android#id$%9Bid/cancel% android#layout_column$%H% android#text$%)ancel% /' "6utton android#id$%9Bid/o% android#text$%,% /'"/ableRow'
1-
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
86/400
Working )ith Containers
-n the pre%eing DML layout $ragment, the Can%el button goes in the thir%olumn &%olumn H'. 4he >E button then goes into the ne:t available%olumn, =hi%h is the $ourth %olumn.
Non-Row Children of Tale!ayout
/ormally, able+ayout %ontains only ableRow elements as immeiate%hilren. )o=ever, it is possible to put other =igets in bet=een ro=s. (orthose =igets, able+ayout behaves a bit like +inear+ayout =ith verti%alorientation. 4he =igets automati%ally have their =ith set to fill_parent,so they =ill $ill the same spa%e that the longest ro= oes.
>ne pattern $or this is to use a plain7iew
as a ivier &e.g.,"7iew
android#layout_&eig&t $ %Hpx% android#bacground $ %@@@@EE% /'as a t=opi:elhigh blue bar a%ross the =ith o$ the table'.
"tret#h$ "hrin%$ and Collapse
y e$ault, ea%h %olumn =ill be sie a%%oring to the QnaturalQ sie o$ the=iest =iget in that %olumn &taking spanne %olumns into a%%ount'.#ometimes, though, that oes not =ork out very =ell, an you nee more
%ontrol over %olumn behavior.
@ou %an pla%e an android#stretc&)olumnsproperty on the able+ayout. 4hevalue shoul be a single %olumn number &again, @base' or a %ommaelimite list o$ %olumn numbers. 4hose %olumns =ill be stret%he to takeup any available spa%e yet on the ro=. 4his helps i$ your %ontent is narro=erthan the available spa%e.
Conversely, you %an pla%e a android#s&rin)olumns property on the
able+ayout. Again, this shoul be a single %olumn number or a %ommaelimite list o$ %olumn numbers. 4he %olumns liste in this property =illtry to =or=rap their %ontents to reu%e the e$$e%tive =ith o$ the %olumn Oby e$ault, =igets are not =or=rappe. 4his helps i$ you have %olumns
=ith potentially =ory %ontent that might %ause some %olumns to be pusheo$$ the right sie o$ the s%reen.
1$
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
87/400
Working )ith Containers
@ou %an also leverage an android#collapse)olumns property on theable+ayout, again =ith a %olumn number or %ommaelimite list o$%olumn numbers. 4hese %olumns =ill start out Q%ollapseQ, meaning they
=ill be part o$ the table in$ormation but =ill be invisible. !rogrammati%ally,
you %an %ollapse an un%ollapse %olumns by %alling set)olumn)ollapsed:;on the able+ayout. @ou might use this to allo= users to %ontrol =hi%h%olumns are o$ importan%e to them an shoul be sho=n versus =hi%h onesare less important an %an be hien.
@ou %an also %ontrol stret%hing an shrinking at runtime viaset)olumnStretc&able:;an set)olumnS&rinable:;.
E.mple
4he DML layout $ragments sho=n above, =hen %ombine, give us aable+ayoutrenition o$ the Q$ormQ =e %reate $or Relative+ayout, =ith theaition o$ a ivier line bet=een the labelU$iel an the t=o buttons&$oun in the ableemo'*
">xml version$%?.@% encoding$%utf-%>'"able+ayout xmlns#android$%&ttp#//sc&emas.android.com/ap/res/android% android#layout_widt&$%fill_parent%
android#layout_&eig&t$%fill_parent% android#stretc&)olumns$%?%' "ableRow' "ext7iew android#text$%2R+#% /' "*ditext android#id$%9Bid/entry% android#layout_span$%I%/' "/ableRow' "7iew android#layout_&eig&t$%Hpx% android#bacground$%@@@@EE% /' "ableRow' "6utton android#id$%9Bid/cancel%
android#layout_column$%H% android#text$%)ancel% /' "6utton android#id$%9Bid/o% android#text$%,% /' "/ableRow'"/able+ayout'
10
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
88/400
Working )ith Containers
When %ompile against the generate Gava %oe an run on the emulator,=e get*
igure *4< The Tableayout/emo sample application
Scroll)ork
!hone s%reens ten to be small, =hi%h re;uires evelopers to use sometri%ks to present a lot o$ in$ormation in the limite available spa%e. >netri%k $or oing this is to use s%rolling, so only part o$ the in$ormation is
visible at one time, the rest available via s%rolling up or o=n.
Scroll7iewis a %ontainer that provies s%rolling $or its %ontents. @ou %antake a layout that might be too big $or some s%reens, =rap it in a Scroll7iew,an still use your e:isting layout logi%. -t Nust so happens that the user %an
only see part o$ your layout at one time, the rest available via s%rolling.
(or e:ample, here is a Scroll7iewuse in an DML layout $ile &$rom the Scrollemo'*
11
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
89/400
Working )ith Containers
">xml version$%?.@% encoding$%utf-%>'"Scroll7iew xmlns#android$%&ttp#//sc&emas.android.com/ap/res/android% android#layout_widt&$%fill_parent% android#layout_&eig&t$%wrap_content%' "able+ayout
android#layout_widt&$%fill_parent% android#layout_&eig&t$%fill_parent% android#stretc&)olumns$%@%' "ableRow' "7iew android#layout_&eig&t$%@px% android#bacground$%@@@@@@%/' "ext7iew android#text$%@@@@@@% android#padding+eft$%Opx% android#layout_gravity$%center_vertical% /' "/ableRow' "ableRow' "7iew
android#layout_&eig&t$%@px% android#bacground$%OO@@@@% /' "ext7iew android#text$%OO@@@@% android#padding+eft$%Opx% android#layout_gravity$%center_vertical% /' "/ableRow' "ableRow' "7iew android#layout_&eig&t$%@px% android#bacground$%OO@@% /' "ext7iew android#text$%OO@@% android#padding+eft$%Opx% android#layout_gravity$%center_vertical% /' "/ableRow'
"ableRow' "7iew android#layout_&eig&t$%@px% android#bacground$%aaOO% /' "ext7iew android#text$%aaOO% android#padding+eft$%Opx% android#layout_gravity$%center_vertical% /' "/ableRow' "ableRow' "7iew android#layout_&eig&t$%@px% android#bacground$%ffaa% /' "ext7iew android#text$%ffaa%
android#padding+eft$%Opx% android#layout_gravity$%center_vertical% /' "/ableRow' "ableRow' "7iew android#layout_&eig&t$%@px% android#bacground$%ffffaa% /' "ext7iew android#text$%ffffaa% android#padding+eft$%Opx%
14
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
90/400
Working )ith Containers
android#layout_gravity$%center_vertical% /' "/ableRow' "ableRow' "7iew android#layout_&eig&t$%@px% android#bacground$%ffffff% /'
"ext7iew android#text$%ffffff% android#padding+eft$%Opx% android#layout_gravity$%center_vertical% /' "/ableRow' "/able+ayout'"/Scroll7iew'
Without the Scroll7iew, the table =oul take up at least B30 pi:els &1 ro=s at80 pi:els ea%h, base on the 7iewe%larations'. 4here may be some evi%es
=ith s%reens %apable o$ sho=ing that mu%h in$ormation, but many =ill besmaller. 4he Scroll7iewlets us keep the table asis, but only present part o$
it at a time.
>n the sto%k Anroi emulator, =hen the a%tivity is $irst vie=e, you see*
igure *7< The ScrollFie)/emo sample application
/oti%e ho= only $ive ro=s an part o$ the si:th are visible. y pressing theupUo=n buttons on the ire%tional pa, you %an s%roll up an o=n to see
17
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
91/400
Working )ith Containers
the remaining ro=s. Also note ho= the right sie o$ the %ontent gets %lippeby the s%rollbar O be sure to put some paing on that sie or other=iseensure your o=n %ontent oes not get %lippe in that $ashion.
19
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
92/400
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
93/400
CHAPTER /
>sing Selection Widgets
a%k in the %hapter on basi% =igets, you sa= ho= $iels %oul have
%onstraints pla%e upon them to limit possible input, su%h as numeri%onlyor phonenumberonly. 4hese sorts o$ %onstraints help users Qget it rightQ
=hen entering in$ormation, parti%ularly on a mobile evi%e =ith %rampekeyboars.
>$ %ourse, the ultimate in %onstraine input is to sele%t a %hoi%e $rom a seto$ items, su%h as the raio buttons seen earlier. Classi% "- toolkits havelistbo:es, %ombobo:es, ropo=n lists, an the like $or that very purpose.
Anroi has many o$ the same sorts o$ =igets, plus others o$ parti%ular
interest $or mobile evi%es &e.g., the 0allery$or e:amining save photos'.
Moreover, Anroi o$$ers a $ le:ible $rame=ork $or etermining =hat %hoi%esare available in these =igets. #pe%i$i%ally, Anroi o$$ers a $rame=ork o$ata aapters that provie a %ommon inter$a%e to sele%tion lists ranging$rom stati% arrays to atabase %ontents. #ele%tion vie=s O =igets $orpresenting lists o$ %hoi%es O are hane an aapter to supply the a%tual%hoi%es.
(dapting to the Circumstances
-n the abstra%t, aapters provie a %ommon inter$a%e to multiple isparateA!-s. More spe%i$i%ally, in Anroi6s %ase, aapters provie a %ommoninter$a%e to the ata moel behin a sele%tionstyle =iget, su%h as a listbo:.
4*
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
94/400
>sing Selection Widgets
4his use o$ Gava inter$a%es is $airly %ommon &e.g., GavaU#=ing6s moelaapters $or =able', an Gava is $ar $rom the only environment o$$ering thissort o$ abstra%tion &e.g., (le:6s DML atabining $rame=ork a%%epts DMLinline as stati% ata or retrieve $rom the -nternet'.
Anroi6s aapters are responsible $or proviing the roster o$ ata $or asele%tion =iget plus %onverting iniviual elements o$ ata into spe%i$i%
vie=s to be isplaye insie the sele%tion =iget. 4he latter $a%et o$ theaapter system may soun a little o, but in reality it is not that i$$erent$rom other 7"- toolkits6 =ays o$ overriing e$ault isplay behavior. (ore:ample, in GavaU#=ing, i$ you =ant a =+istba%ke listbo: to a%tually be a%he%klist &=here iniviual ro=s are a %he%kbo: plus label, an %li%ks aNustthe state o$ the %he%kbo:', you inevitably =in up %alling set)ellRenderer:;
to supply your o=n +ist)ellRenderer, =hi%h in turn %onverts strings $or thelist into =)&ec6oxplus=+abel%omposite =igets.
+sin! ArryAdpter
4he easiest aapter to use is ArrayAdapterO all you nee to o is =rap one o$these aroun a Gava array or java.util.+istinstan%e, an you have a $ully$un%tioning aapter*
StringPQitems$8%t&is%G%is%G%a%G %really%G%silly%G%list%
-
8/13/2019 Android 1 2 CC
95/400
>sing Selection Widgets
into ext7iewobNe%ts. 4hose ext7iew=igets, in turn, =ill be sho=n the listor spinner or =hatever =iget uses this ArrayAdapter.
@ou %an sub%lass ArrayAdapter an overrie get7iew:; to Qroll your o=nQ
vie=s*
public7iew getView:intpositionG7iew convert7iewG 7iew0roup parent;8 if:convert7iew$$null;8 convert7iew$newTextView:t&is;5 xml version$%?.@% encoding$%utf-%>'
"+inear+ayout xmlns#android$%&ttp#//sc&emas.android.com/ap/res/android% android#orientation$%vertical% android#layout_widt&$%fill_parent%
android#layout_&eig&t$%fill_parent% ' "ext7iew android#id$%9Bid/selection% android#layout_widt&$%fill_parent% android#layout_&eig&t$%wrap_content%/' "+ist7iew android#id$%9android#id/list% android#layout_widt&$%fill_parent%
android#layout_&eig&t$%fill_parent%
android#drawSelector,nop$%false% /'"/+inear+ayout'
-t is Nust a list =ith a label on top to sho= the %urrent sele%tion.
4$
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
97/400
>sing Selection Widgets
4he Gava %oe to %on$igure the list an %onne%t the list =ith the label is*
publicclass+ist7iewDemo extends+istActivity 8 ext7iew selection5 StringPQitems$8%lorem%G%ipsum%G%dolor%G%sit%G%amet%G
%consectetuer%G%adipiscing%G%elit%G%morbi%G%vel%G %ligula%G%vitae%G%arcu%G%aliJuet%G%mollis%G %etiam%G%vel%G%erat%G%placerat%G%ante%G %porttitor%G%sodales%G%pellentesJue%G%augue%G%purus%
-
8/13/2019 Android 1 2 CC
98/400
>sing Selection Widgets
igure *9< The istFie)/emo sample application
Spin Control
-n Anroi, the Spinner is the e;uivalent o$ the ropo=n sele%tor youmight $in in other toolkits &e.g., =)ombo6oxin GavaU#=ing'. !ressing the le$t
an right buttons on the pa iterates over %hilren. !ressing the %enterbutton on the pa isplays, by e$ault, a small list &akin to a +ist7iew'appears to sho= a $e= items at a time, instea o$ the oneitematatimeperspe%tive the une:pane Spinneritsel$ provies.
As =ith +ist7iew, you provie the aapter $or ata an %hil vie=s viasetAdapter:; an hook in a listener obNe%t $or sele%tions viaset,ntemSelected+istener:; .
-$ you =ant to tailor the vie= use =hen isplaying the ropo=nperspe%tive, you nee to %on$igure the aapter, not the Spinner=iget. "sethe setDropDown7iewResource:; metho to supply the resour%e - o$ the vie=to use.
41
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
99/400
>sing Selection Widgets
(or e:ample, %ulle $rom the Spinnersample proNe%t, here is an DML layout$or a simple vie= =ith a Spinner*
">xml version$%?.@% encoding$%utf-%>'"+inear+ayout xmlns#android$%&ttp#//sc&emas.android.com/ap/res/android% android#orientation$%vertical% android#layout_widt&$%fill_parent% android#layout_&eig&t$%fill_parent% ' "ext7iew android#id$%9Bid/selection% android#layout_widt&$%fill_parent% android#layout_&eig&t$%wrap_content% /' "Spinner android#id$%9Bid/spinner% android#layout_widt&$%fill_parent% android#layout_&eig&t$%wrap_content%
android#drawSelector,nop$%true% /'"/+inear+ayout'
4his is the same vie= as sho=n in the previous se%tion, Nust =ith a Spinnerinstea o$ a +ist7iew. 4he Spinner property android#drawSelector,nop%ontrols =hether the arro=s are ra=n on the sele%tor button on the rightsie o$ the Spinner"-.
4o populate an use the Spinner, =e nee some Gava %oe*
publicclassSpinnerDemo extendsActivity implementsAdapter7iew.,ntemSelected+istener 8 ext7iew selection5 StringPQitems$8%lorem%G%ipsum%G%dolor%G%sit%G%amet%G %consectetuer%G%adipiscing%G%elit%G%morbi%G%vel%G %ligula%G%vitae%G%arcu%G%aliJuet%G%mollis%G %etiam%G%vel%G%erat%G%placerat%G%ante%G %porttitor%G%sodales%G%pellentesJue%G%augue%G%purus%
-
8/13/2019 Android 1 2 CC
100/400
>sing Selection Widgets
items;5
aa.setDropDownView$esource: android.R.layout.simple_spinner_dropdown_item;5 spin.set#dapter:aa;5 xml version$%?.@% encoding$%utf-%>'"+inear+ayout xmlns#android$%&ttp#//sc&emas.android.com/ap/res/android% android#orientation$%vertical% android#layout_widt&$%fill_parent% android#layout_&eig&t$%fill_parent% ' "ext7iew android#id$%9Bid/selection% android#layout_widt&$%fill_parent% android#layout_&eig&t$%wrap_content% /' "0rid7iew android#id$%9Bid/grid% android#layout_widt&$%fill_parent%
android#layout_&eig&t$%fill_parent% android#verticalSpacing$%ILpx% android#&ori(ontalSpacing$%Lpx% android#num)olumns$%auto_fit% android#columnCidt&$%?@@px% android#stretc&Mode$%columnCidt&% android#gravity$%center% /'"/+inear+ayout'
(or this gri, =e take up the entire s%reen e:%ept $or =hat our sele%tion labelre;uires. 4he number o$ %olumns is %ompute by Anroi
&android#num)olumns $ %auto_fit%' base on Bpi:el horiontal spa%ing&android#&ori(ontalSpacing $ %L%', 00pi:el %olumns &android#columnCidt&$ %?@@%', =ith the %olumns absorbing any QslopQ =ith le$t over&android#stretc&Mode $ %columnCidt&%'.
4he Gava %oe to %on$igure the 0rid7iewis*
publicclass0ridDemo extendsActivity implementsAdapter7iew.,ntemSelected+istener 8 ext7iew selection5
StringPQitems$8%lorem%G%ipsum%G%dolor%G%sit%G%amet%G %consectetuer%G%adipiscing%G%elit%G%morbi%G%vel%G %ligula%G%vitae%G%arcu%G%aliJuet%G%mollis%G %etiam%G%vel%G%erat%G%placerat%G%ante%G %porttitor%G%sodales%G%pellentesJue%G%augue%G%purus%
-
8/13/2019 Android 1 2 CC
104/400
-
8/13/2019 Android 1 2 CC
105/400
>sing Selection Widgets
ext7iew, =e Nust reset its te:tP other=ise, =e %reate a ne= ext7iewinstan%ean populate it.
With the ?Bpi:el verti%al spa%ing $rom the DML layout
&android#verticalSpacing $ %IL%', the gri over$lo=s the bounaries o$ theemulator6s s%reen*
igure %%< The 'rid/emo sample application6 as initially launched
7-
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
106/400
>sing Selection Widgets
igure %-< The same application6 scrolled to the bottom of the grid
ieldsH 5o) With -0I ess Typing!
4he Auto)ompleteext7iewis sort o$ a hybri bet=een the *dit7iew&$iel' anthe Spinner. With auto%ompletion, as the user types, the te:t is treate as a
pre$i: $ilter, %omparing the entere te:t as a pre$i: against a list o$%aniates. Mat%hes are sho=n in a sele%tion list that, like =ith Spinner,$ols o=n $rom the $iel. 4he user %an either type out an entry &e.g.,something not in the list' or %hoose an entry $rom the list to be the value o$the $iel.
Auto)ompleteext7iew sub%lasses *dit7iew, so you %an %on$igure all thestanar lookan$eel aspe%ts, su%h as $ont $a%e an %olor.
-n aition, Auto)ompleteext7iew has a android#completion&res&oldproperty, to ini%ate the minimum number o$ %hara%ters a user must enterbe$ore the list $iltering begins.
@ou %an give Auto)ompleteext7iew an aapter %ontaining the list o$%aniate values via setAdapter:;. )o=ever, sin%e the user %oul type
7$
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
107/400
>sing Selection Widgets
something not in the list, Auto)ompleteext7iewoes not support sele%tionlisteners. -nstea, you %an register a extCatc&er, like you %an =ith any*dit7iew, to be noti$ie =hen the te:t %hanges. 4hese events =ill o%%ureither be%ause o$ manual typing or $rom a sele%tion $rom the ropo=n
list.
elo= =e have a $amiliarlooking DML layout, this time %ontaining anAuto)ompleteext7iew&pulle $rom the Auto)ompletesample appli%ation'*
">xml version$%?.@% encoding$%utf-%>'"+inear+ayout xmlns#android$%&ttp#//sc&emas.android.com/ap/res/android% android#orientation$%vertical% android#layout_widt&$%fill_parent% android#layout_&eig&t$%fill_parent%
' "ext7iew android#id$%9Bid/selection% android#layout_widt&$%fill_parent% android#layout_&eig&t$%wrap_content% /' "Auto)ompleteext7iew android#id$%9Bid/edit% android#layout_widt&$%fill_parent% android#layout_&eig&t$%wrap_content% android#completion&res&old$%I%/'"/+inear+ayout'
4he %orresponing Gava %oe is*
publicclassAuto)ompleteDemo extendsActivity implementsextCatc&er 8 ext7iew selection5 Auto)ompleteext7iew edit5 StringPQitems$8%lorem%G%ipsum%G%dolor%G%sit%G%amet%G %consectetuer%G%adipiscing%G%elit%G%morbi%G%vel%G %ligula%G%vitae%G%arcu%G%aliJuet%G%mollis%G %etiam%G%vel%G%erat%G%placerat%G%ante%G %porttitor%G%sodales%G%pellentesJue%G%augue%G%purus%
-
8/13/2019 Android 1 2 CC
108/400
>sing Selection Widgets
android.R.layout.simple_list_item_?G items;;5 ne %hoi%e $ollo=s the ne:t a%ross the
horiontal plane, =ith the %urrentlysele%te item highlighte. >n anAnroi evi%e, one rotates through the options through the le$t an rightpa buttons.
Compare to the +ist7iew, the 0allerytakes up less s%reen spa%e =hile stillsho=ing multiple %hoi%es at one time &assuming they are short enough'.Compare to the Spinner, the 0alleryal=ays sho=s more than one %hoi%e ata time.
4he ;uintessential e:ample use $or the 0alleryis image previe= O given a%olle%tion o$ photos or i%ons, the 0allerylets people previe= the pi%tures inthe pro%ess o$ %hoosing one.
Coe=ise, the 0allery=orks mu%h like a Spinneror 0rid7iew. -n your DMLlayout, you have a $e= properties at your isposal*
android#spacing%ontrols the number o$ pi:els bet=een entries in thelist
android#spinnerSelector%ontrols =hat is use to ini%ate a sele%tionO this %an either be a re$eren%e to a Drawable &see the resour%es%hapter' or an R7 value in AARR0066or similar notation
android#drawSelector,nopini%ates i$ the sele%tion bar &or Drawable'shoul be ra=n be$ore &false' or a$ter &true' ra=ing the sele%te%hil O i$ you %hoose true, be sure that your sele%tor has su$$i%ienttransparen%y to sho= the %hil through the sele%tor, other=ise users
=ill not be able to rea the sele%tion
77
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
-
8/13/2019 Android 1 2 CC
111/400
CHAPTER 2
'etting ancy With ists
4he humble +ist7iewis one o$ the most important =igets in all o$ Anroi,
simply be%ause it is use so $re;uently. Whether %hoosing a %onta%t to %allor an email message to $or=ar or an ebook to rea, +ist7iew=igets areemploye in a =ie range o$ a%tivities.
>$ %ourse, it =oul be ni%e i$ they =ere more than Nust plain te:t.
4he goo ne=s is that they %an be as $an%y as you =ant, =ithin thelimitations o$ a mobile evi%e6s s%reen, o$ %ourse. )o=ever, making them$an%y takes some =ork an some $eatures o$ Anroi that =e =ill %over inthis %hapter.
4he material in this %hapter is base on the author6s posts to the uiling6rois%olumn onAnroi7uys.%om.
'etting To irst Base
4he %lassi% Anroi +ist7iew is a plain list o$ te:t V soli but uninspiring.
4his is be%ause all =e have hane to the +ist7iewis a bun%h o$ =ors in anarray, an tol Anroi to use a simple builtin layout $or pouring those
=ors into a list.
79
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition
http://androidguys.com/category/building-droids/http://androidguys.com/category/building-droids/http://androidguys.com/category/building-droids/http://androidguys.com/http://androidguys.com/category/building-droids/http://androidguys.com/category/building-droids/http://androidguys.com/ -
8/13/2019 Android 1 2 CC
112/400
'etting ancy With ists
)o=ever, you %an have a list =hose ro=s are mae up o$ i%ons, or i%ons ante:t, or %he%kbo:es an te:t, or =hatever you =ant. -t is merely a matter o$supplying enough ata to the aapter an helping the aapter to %reate ari%her set o$ 7iewobNe%ts $or ea%h ro=.
(or e:ample, suppose you =ant a +ist7iew=hose entries are mae up o$ ani%on, $ollo=e by some te:t. @ou %oul %onstru%t a layout $or the ro= thatlooks like this, $oun in the Staticsample proNe%t*
">xml version$%?.@% encoding$%utf-%>'"+inear+ayout xmlns#android$%&ttp#//sc&emas.android.com/ap/res/android% android#layout_widt&$%fill_parent% android#layout_&eig&t$%wrap_content% android#orientation$%&ori(ontal%'
"mage7iew android#id$%9Bid/icon% android#layout_widt&$%HHpx% android#padding+eft$%Hpx% android#paddingRig&t$%Hpx% android#paddingop$%Hpx% android#layout_&eig&t$%wrap_content% android#src$%9drawable/o% /' "ext7iew android#id$%9Bid/label% android#layout_widt&$%wrap_content% android#layout_&eig&t$%wrap_content%
android#textSi(e$%OOsp% /'"/+inear+ayout'
4his layout uses a +inear+ayoutto set up a ro=, =ith the i%on on the le$t anthe te:t &in a ni%e big $ont' on the right.
y e$ault, though, Anroi has no iea that you =ant to use this layout=ith your +ist7iew. 4o make the %onne%tion, you nee to supp