android ui基础教程
AndroidUlFundamentals:Developanddesign
PeachpitPress
1249EighthStreet
510/524-2178
510/524-2221(fax)
FindusontheWebatwww.peachpit.com
Toreporterrorspleasesendanotetoerrata@peachpit.com
PeachpitPressisadivisionofPearsoneducation
opyrightC2012byJasonOstrander
Editor:CliffordColby
Developmenteditor:RobynThomas
navlado
Technicaleditor:JasonLebrun
raiger
nteriordesign:MimiHeft
Compositor:DanielleFoster
Indexer:ValerieHaynesPerry
Noticeofrights
Allrightsreserved.Nopartofthisbookmaybereproducedortransmittedinanyformbyanymeans,
electronic,mechanical,photocopying,recording,orotherwise,withoutthepriorwrittenpermissionofthe
publisherForinformationongettingpermissionforreprintsandexcerptscontactpermissions@peachpit.com
Noticeofliabilit
Theinformationinthisbookisdistributedonan"AsIs"basiswithoutwarranty.Whileeveryprecautionhas
beentakeninthepreparationofthebook,neithertheauthornorPeachpitshallhaveanyliabilitytoany
personorentitywithrespecttoanylossordamagecausedorallegedtobecauseddirectlyorindirectlyby
theinstructionscontainedinthisbookorbythecomputersoftwareandhardwareproductsdescribedinit
Trademarks
AndroidisatrademarkofGoogleInc,registeredintheUnitedStatesandothercountries.Manyofthe
designationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedastrademarks
Wherethosedesignationsappearinthisbook,andPeachpitwasawareofatrademarkclaim,thedesigna
tionsappearasrequestedbytheownerofthetrademark.Allotherproductnamesandservicesidentified
throughoutthisbookareusedineditorialfashiononlyandforthebeneftofsuchcompanieswithno
intentionofinfringementofthetrademark.Nosuchuse,ortheuseofanytradename,isintendedto
conveyendorsementorotheraffiliationwiththisbook
ISBN13:978-0-321-81458-6
ISBN10
0-321-81458-4
987654321
Printedandboundintheunitedstatesofamerica
mylovelywife,St
whotirelesslysupportsmeinallofmyadventures
ACKNOWLEDGMENTS
icouldwriteanentirebookthankingpeoplefortheirhelpalongtheway.Instead,
I'llhavetosettleforthisshortparagraph
ThankstoChrisH.forpushingmetoconsiderwritingabookandgivingme
endlessencouragementandsupportToCliffCforgivingmethechancetowrite
thisbook.ToRobynTforkeepingmeonscheduledespitemybestefforts.To
JBLforfixingmycodeandrockingameanbassguitar.ToScoutFandMyrnav.
forworkingtirelesslywhenIwaslategettingchapterstothem.ToLucasDand
RobSforreadingearlychaptersandgivingmevaluablefeedback.Totheentire
teamatdoubletwistfortheirdedicationtomakinggreatandroidsoftware.To
theandroidteamatGoogleforcreatingagreatplatform.Tomyfamilyfortheir
continuingsupportdespitemydroppingoffthefaceoftheearthToPeachpitfor
givingmetheopportunitytowritethisforyou.Andtoyou,thereader,forgiving
methechancetoteachyouinwhateversmallwayIcan
JasonOstranderisawebandmobilesoftwaredeveloperworkingatSiliconValley
startupdoubleTwist,wherehemakessyncingmediatoandroidphonessimple
Priortothat,hesolvednetworkingproblemsatenergymanagementstartup
SentillaanddefensecompanyNorthropGrumman.JasonholdsanMSinelectrical
engineeringfromUCLA.HeliveswithhiswifeinSanFrancisco'sMissionDistrict
wherehespendshistimesearchingfortheperfectchilerelle
IVANDROIDUIFUNDAMENTALS:DEVELOPANDDESIGN
CONTENTS
Introduction
Welcometoandroid
PART1BASICANDROIDUI
CHAPTER1GETTINGSTARTED
BasicStructureofanAndroidapp
Androiduibasics
14
Tools
22
1gU1
32
CHAPTER2CREATINGYOURFIRSTAPPLICATION
...34
CreatinganApp
36
GettingStartedwithAndroidviews
ArrangingViews
41
Displayingalist
52
UnderstandingActivities
57
PreventingANRs
64
FinishingtheTimeTrackerApp
WrappingUp
CHAPTER3GOINGFURTHER.......................74
SupportingMultipleScreenSizes
Handlingnotifications
84
Handlingevents
Creatingmenus
96
ImplementingtheTimeTracker
102
ppingup
107
CONTENTsV
PART2THEVIEWFRAMEWORK
CHAPTER4
BASICVIEWS
...,110
CreatingaBasicform
112
DisplayingImage
CreatingMapsandDisplayingWebsite
130
WrappingUp
136
CHAPTER5REUSABLEUI.........................138
AbstractingYourlayouts
140
AbstractingStylesandThemes
UsingFragments
Wrappingup
CHAPTER6NAVIGATIONANDDATALOADING
.164
IntroducingtheActionBar
166
NavigatingYourApp
172
LoadingdataintoViews
181
appingup
186
CHAPTER7ANDROIDWIDGETS
188
CreatingaBasicwidget
190
CreatingaCollectionWidget
Wrappingup
VIANDROIDUIFUNDAMENTALS:DEVELOPANDDESIGN
PaRT3ADVANCEDUIDEVELOPMENT
CHAPTERHANDLINGGESTUres
..214
ListeningtoTouchEvents
216
RespondingtoGestures
224
pping
229
CHAPTER9ANIMATION..........
..230
Creatingdrawableanimations
232
Creatingviewanimations
235
CreatingPropertyanimations
246
WrappingUp
CHAPTER10CREATINGCUSTOMVIEWS
.256
UnderstandingHowandroidDrawsviews
CreatingaCustomView
259
AddingCustomAttributestoYourCustomviews
267
CreatingCompoundComponents
2
WrappingUp
279
CHAPTER11CREATINGADVANCEDGRAPHICS
280
USingcanvas
282
UsingRenderScript
USingOpenGL
294
WrappingUp
3O1
CHAPTER12LOCALIZATIONANDACCESSIBILITY302
MakingYourAppAvailableinMultipleLanguages
304
MakingYourAppaccessible
309
WrappingUp
315
316
CoNTENTsVII
INTRODUCTION
Thereisarevolutionhappeninginthetechnologyindustry.Touchscreeninterfaces
combinedwithlow-costandubiquitoussmartphones,havecreatedaperfectstorm
fordisruptiveinnovation.androidisattheforefrontofthischangebringingafree
andopen-sourceplatformonwhichdeveloperscancreatethenextgenerationof
applications.Withfreedevelopmenttoolsandanopenmarket,anyonecandevelop
applicationsthatreachaworldwidemarket.Butwhychoosetodevelopforandroid?
AndroidnowrunsonthemajorityofsmartphonesintheUnitedStatesAnd
it'squicklyexpandingintonewmarketsanddevicetypes.Thelastyearhasseen
theintroductionofhundredsofAndroid-basedtablets,includingthehitKindle
Fire.GooglehasportedandroidtoTVswithitsGoogleTVplatform,andmany
manufacturersarebeginningtoshipTVswithAndroidbuiltin.Boeinghasselected
AndroidastheentertainmentplatformforitsnewDreamlinerjetFordisintegrat-
ingAndroidintoitsin-dashSYNCentertainmentsystem.AndAndroidisquickly
gainingtractioninthedevelopingworld,especiallyinAfrica,wheretheneedfor
low-costhandsetsisgreatest
Yetforalloftheplatformspromisethemajorityofandroidapplicationsstill
lackthevisualpolishoftheirioScounterparts.Thisbookaimstoaddressthat
issuebyprovidingdeveloperswithasolidfoundationforbuildingappUIs.Itwill
coverthebasicsofuidevelopmentonAndroid,teachbestpracticesforcreating
flexiblelayouts,andgiveyoutipsonhowtooptimizeyourUIforsmooth,fluid
performance.icreatedthisbookinthehopethatitwillhelpdeveloperstocreate
beautifulapplications
WhoamI?I'vebeendevelopingsoftwareprofessionallyforalmosttenyears
andI'vefocusedonembeddedandmobilesoftwareforthelastfive.Inmydayjob
Iworkforoneofthetopandroiddevelopmentcompaniesandwritecodethat
millionsofpeopleuseeveryday
Androiddevelopmentcanbedifficultattimes,andthechallengesofsupporting
suchadiversityofdevicescanbedaunting.Butwithagoodidea,asolidunder
standingoftheframework,andalittlepersistence,anyonecancreateagreatapp
thatisusedbymillionsofpeople
ihopeyou'llenjoyreadingthisbookasmuchasienjoyedwritingitforyou
VIlANDROidUIFUNDAMENTALS:DEVELOPANDDESIGN
WHOTHISBOOKISFOR
ThisbookisaimedatbeginningAndroiddeveloperswhoareinterestedincreating
greatuserinterfaces.YouareexpectedtoknowbasicJavaprogrammingandXML
syntax.ThefocusofthisbookisonUI.Whileyoudontneedtohaveexperience
writingAndroidsoftware,manybasicandroidconceptsareonlydescribedin
passing.Itwillhelpyoutohavearudimentaryknowledgeofandroiddevelopment
WHOTHISBOOKISNOTFOR
Thisbookisnotageneralintroductiontoprogrammingforandroid.whileitis
intendedforbeginningAndroiddevelopers,thefocusisonuserinterfacetools
andprogramming.Inparticular,thisbookwillnotcoverbasicAndroidconcepts
suchasintents,services,orcontentproviders.Further,thisbookwillnotbean
introductiontotheJavaprogramminglanguageortoXML.Youshouldknowhow
toprogramandhowtoreadXML
HOWYOUWILLLEARN
Throughoutthisbook,you'lllearnbycreatinganactualapp,asimpletime
tracker.Eachchapterincludesdetailedexamplesofrealandroidcodethatyou
willcompileandrun.allcodeforthebookcanbefoundatthebook'swebsite
www.peachpit.com/androiduifundamentals
WHATYOUWILLLEARN
You'lllearnhowtocreateuserinterfacesforAndroidapplicationsFromthemost
basicconcepts,likeactivitiesandviews,allthewaytoadvancedgraphicsusing
Renderscript,thisbookcoverseverythingyouwillusetobuildtheuserinterface
ofyourapps
ANOTEABOUTANDROIDVERSIONS
ThisbookwaswrittentoAndroidversion4APIsandbestpractices,butitiscom
patiblebacktoandroidversion2.2.Whenrelevant,notesandtipsareincludedto
indicatewhenanaPiisdeprecatedornolongerappropriate.Theandroidcom
patibilitylibrary,apackageofclassesthatback-portseveralnewerfeatures,will
beusedthroughoutthebook
INTRODUCTIONX
用户评论