构建你的第一个Android应用程序.docx
《构建你的第一个Android应用程序.docx》由会员分享,可在线阅读,更多相关《构建你的第一个Android应用程序.docx(11页珍藏版)》请在冰豆网上搜索。
构建你的第一个Android应用程序
编写你的第一个Android应用程序
2012-10-3翻译:
罗奕聪
注意:
這篇文章的一部分基於Android開放原始碼計劃(AndroidOpenSourceProject),這部分內容在知識共享姓名標示2.5(CCBY2.5)許可下發佈此內容在知識共享姓名標示-非商業性-相同方式分享3.0Unported(CCBY-NC-SA3.0)許可下發佈。
一、创建一个Android工程
AnAndroidprojectcontainsallthefilesthatcomprisethesourcecodeforyourAndroidapp.TheAndroidSDKtoolsmakeiteasytostartanewAndroidprojectwithasetofdefaultprojectdirectoriesandfiles.
ThislessonshowshowtocreateanewprojecteitherusingEclipse(withtheADTplugin)orusingtheSDKtoolsfromacommandline.
CreateaProjectwithEclipse
InEclipse,clickNewAndroidAppProject
inthetoolbar.
Figure1. TheNewAndroidAppProjectwizardinEclipse.
1.Fillintheformthatappears:
oApplicationName istheappnamethatappearstousers.Forthisproject,use"MyFirstApp."
oProjectName isthenameofyourprojectdirectoryandthenamevisibleinEclipse.
oPackageName isthepackagenamespaceforyourapp(followingthesamerulesaspackagesintheJavaprogramminglanguage).YourpackagenamemustbeuniqueacrossallpackagesinstalledontheAndroidsystem.Forthisreason,it'sgenerallybestifyouuseanamethatbeginswiththereversedomainnameofyourorganizationorpublisherentity.Forthisproject,youcanusesomethinglike"com.example.myfirstapp."However,youcannotpublishyourapponGooglePlayusingthe"com.example"namespace.
oBuildSDK istheplatformversionagainstwhichyouwillcompileyourapp.Bydefault,thisissettothelatestversionofAndroidavailableinyourSDK.(ItshouldbeAndroid4.1orgreater;ifyoudon'thavesuchaversionavailable,youmustinstalloneusingthe SDKManager).Youcanstillbuildyourapptosupportolderversions,butsettingthebuildtargettothelatestversionallowsyoutoenablenewfeaturesandoptimizeyourappforagreatuserexperienceonthelatestdevices.
oMinimumRequiredSDK isthelowestversionofAndroidthatyourappsupports.Tosupportasmanydevicesaspossible,youshouldsetthistothelowestversionavailablethatallowsyourapptoprovideitscorefeatureset.IfanyfeatureofyourappispossibleonlyonnewerversionsofAndroidandit'snotcriticaltotheapp'scorefeatureset,youcanenablethefeatureonlywhenrunningontheversionsthatsupportit.
Leavethissettothedefaultvalueforthisproject.
2.Click Next.
3.Thefollowingscreenprovidestoolstohelpyoucreatealaunchericonforyourapp.
Youcancustomizeaniconinseveralwaysandthetoolgeneratesaniconforallscreendensities.Beforeyoupublishyourapp,youshouldbesureyouriconmeetsthespecificationsdefinedinthe Iconography designguide.
Click Next.
4.Nowyoucanselectanactivitytemplatefromwhichtobeginbuildingyourapp.
Forthisproject,select BlankActivity andclick Next.
5.Leaveallthedetailsfortheactivityintheirdefaultstateandclick Finish.
YourAndroidprojectisnowsetupwithsomedefaultfilesandyou’rereadytobeginbuildingtheapp.Continuetothe nextlesson.
CreateaProjectwithCommandLineTools
Ifyou'renotusingtheEclipseIDEwiththeADTplugin,youcaninsteadcreateyourprojectusingtheSDKtoolsfromacommandline:
1.ChangedirectoriesintotheAndroidSDK’s tools/ path.
2.Execute:
androidlisttargets
ThisprintsalistoftheavailableAndroidplatformsthatyou’vedownloadedforyourSDK.Findtheplatformagainstwhichyouwanttocompileyourapp.Makeanoteofthetargetid.Werecommendthatyouselectthehighestversionpossible.Youcanstillbuildyourapptosupportolderversions,butsettingthebuildtargettothelatestversionallowsyoutooptimizeyourappforthelatestdevices.
Ifyoudon'tseeanytargetslisted,youneedtoinstallsomeusingtheAndroidSDKManagertool.See AddingPlatformsandPackages.
3.Execute:
androidcreateproject--target--nameMyFirstApp\--path/MyFirstApp--activityMainActivity\--packagecom.example.myfirstapp
Replace withanidfromthelistoftargets(fromthepreviousstep)andreplace withthelocationinwhichyouwanttosaveyourAndroidprojects.
YourAndroidprojectisnowsetupwithseveraldefaultconfigurationsandyou’rereadytobeginbuildingtheapp.Continuetothe nextlesson.
Tip:
Addthe platform-tools/ aswellasthe tools/ directorytoyour PATH environmentvariable.
RunningYourApp
Ifyoufollowedthe previouslesson tocreateanAndroidproject,itincludesadefaultsetof"HelloWorld"sourcefilesthatallowyoutoimmediatelyruntheapp.
Howyourunyourappdependsontwothings:
whetheryouhavearealAndroid-powereddeviceandwhetheryou’reusingEclipse.ThislessonshowsyouhowtoinstallandrunyourapponarealdeviceandontheAndroidemulator,andinbothcaseswitheitherEclipseorthecommandlinetools.
Beforeyourunyourapp,youshouldbeawareofafewdirectoriesandfilesintheAndroidproject:
AndroidManifest.xml
The manifestfile describesthefundamentalcharacteristicsoftheappanddefineseachofitscomponents.You'lllearnaboutvariousdeclarationsinthisfileasyoureadmoretrainingclasses.
src/
Directoryforyourapp'smainsourcefiles.Bydefault,itincludesan Activity classthatrunswhenyourappislaunchedusingtheappicon.
res/
Containsseveralsub-directoriesfor appresources.Herearejustafew:
drawable-hdpi/
Directoryfordrawableobjects(suchasbitmaps)thataredesignedforhigh-density(hdpi)screens.Otherdrawabledirectoriescontainassetsdesignedforotherscreendensities.
layout/
Directoryforfilesthatdefineyourapp'suserinterface.
values/
DirectoryforothervariousXMLfilesthatcontainacollectionofresources,suchasstringandcolordefinitions.
WhenyoubuildandrunthedefaultAndroidapp,thedefault Activity classstartsandloadsalayoutfilethatsays"HelloWorld."Theresultisnothingexciting,butit'simportantthatyouunderstandhowtorunyourappbeforeyoustartdeveloping.
RunonaRealDevice
IfyouhavearealAndroid-powereddevice,here'showyoucaninstallandrunyourapp:
1.PluginyourdevicetoyourdevelopmentmachinewithaUSBcable.Ifyou’redevelopingonWindows,youmightneedtoinstalltheappropriateUSBdriverforyourdevice.Forhelpinstallingdrivers,seethe OEMUSBDrivers document.
2.Ensurethat USBdebugging isenabledinthedeviceSettings(openSettingsandnavitageto Applications>Development onmostdevices,orclick Developeroptions onAndroid4.0andhigher).
ToruntheappfromEclipse,openoneofyourproject'sfilesandclickRun
fromthetoolbar.Eclipseinstallstheapponyourconnecteddeviceandstartsit.
Ortorunyourappfromacommandline:
1.
antdebug
ChangedirectoriestotherootofyourAndroidprojectandexecute:
2.
adbinstallbin/MyFirstApp-debug.apk
MakesuretheAndroidSDK platform-tools/ directoryisincludedinyour PATH environmentvariable,thenexecute:
3.Onyourdevice,locate MyFirstActivity andopenit.
That'showyoubuildandrunyourAndroidapponadevice!
Tostartdeveloping,continuetothe nextlesson.
RunontheEmulator
Whetheryou’reusingEclipseorthecommandline,torunyourappontheemulatoryouneedtofirstcreateanAndroidVirtualDevice (AVD).AnAVDisadeviceconfigurationfortheAndroidemulatorthatallowsyoutomodeldifferentdevices.
Figure1. TheAVDManagershowingafewvirtualdevices.
TocreateanAVD:
1.LaunchtheAndroidVirtualDeviceManager:
a.InEclipse,clickAndroidVirtualDeviceManager
fromthetoolbar.
b.
androidavd
Fromthecommandline,changedirectoriesto/tools/ andexecute:
2.Inthe AndroidVirtualDeviceManager panel,click New.
3.FillinthedetailsfortheAVD.Giveitaname,aplatformtarget,anSDcardsize,andaskin(HVGAisdefault).
4.Click CreateAVD.
5.SelectthenewAVDfromthe AndroidVirtualDeviceManager andclick Start.
6.Aftertheemulatorbootsup,unlocktheemulatorscreen.
ToruntheappfromEclipse,openoneofyourproject'sfilesandclickRun
fromthetoolbar.EclipseinstallstheapponyourAVDandstartsit.
Ortorunyourappfromthecommandline:
1.ChangedirectoriestotherootofyourAndroidprojectandexecute:
antdebug
2.MakesuretheAndroidSDK platform-tools/ directoryisincludedinyour PATH environmentvariable,thenexecute:
adbinstallbin/MyFirstApp-debug.apk
3.Ontheemulator,locate MyFirstActivity andopenit.
That'showyoubuildandrunyourAndroidappontheemulator!
Tostartdeveloping,continuetothe nextlesson.
BuildingaSimpleUserInterface
AlternativeLayouts
DeclaringyourUIlayoutinXMLratherthanruntimecodeisusefulforseveralreasons,butit'sespeciallyimportantsoyoucancreatedifferentlayoutsfordifferentscreensizes.Forexample,youcancreatetwoversionsofalayoutandtellthesystemtouseoneon"small"screensandtheotheron"large"screens.Formoreinformation,seetheclassabout SupportingDifferentDevices.
ThegraphicaluserinterfaceforanAndroidappisbuiltusingahierarchyof View and ViewGroup objects. View objectsareusuallyUIwidgetssuchas buttons or textfields andViewGroup objectsareinvisibleviewcontainersthatdefinehowthechildviewsarelaidout,suchasinagridoraverticallist.
AndroidprovidesanXMLvocabularythatcorrespondstothesubclassesof View and ViewGroup soyoucandefineyourUIinXMLusingahierarchyofUIelements.
Figure1. Illustrationofhow ViewGroup objectsformbranchesinthelayoutandcontainother View objects.
Inthislesson,you'llcreatealayoutinXMLthatincludesatextfieldandabutton.Int