构建你的第一个Android应用程序Word格式.docx
《构建你的第一个Android应用程序Word格式.docx》由会员分享,可在线阅读,更多相关《构建你的第一个Android应用程序Word格式.docx(11页珍藏版)》请在冰豆网上搜索。
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
4.Nowyoucanselectanactivitytemplatefromwhichtobeginbuildingyourapp.
Forthisproject,select
BlankActivity
andclick
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<
target-id>
--nameMyFirstApp\--path<
path-to-workspace>
/MyFirstApp--activityMainActivity\--packagecom.example.myfirstapp
Replace
<
withanidfromthelistoftargets(fromthepreviousstep)andreplace
withthelocationinwhichyouwanttosaveyourAndroidprojects.
YourAndroidprojectisnowsetupwithseveraldefaultconfigurationsandyou’rereadytobeginbuildingtheapp.Continuetothe
Tip:
Addthe
platform-tools/
aswellasthe
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
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
directoryisincludedinyour
environmentvariable,thenexecute:
3.Onyourdevice,locate
MyFirstActivity
andopenit.
That'
showyoubuildandrunyourAndroidapponadevice!
Tostartdeveloping,continuetothe
RunontheEmulator
Whetheryou’reusingEclipseorthecommandline,torunyourappontheemulatoryouneedtofirstcreateanAndroidVirtualDevice
(AVD).AnAVDisadeviceconfigurationfortheAndroidemulatorthatallowsyoutomodeldifferentdevices.
TheAVDManagershowingafewvirtualdevices.
TocreateanAVD:
1.LaunchtheAndroidVirtualDeviceManager:
a.InEclipse,clickAndroidVirtualDeviceManager
fromthetoolbar.
b.
androidavd
Fromthecommandline,changedirectoriesto<
sdk>
/tools/
andexecute:
2.Inthe
AndroidVirtualDeviceManager
panel,click
New.
3.FillinthedetailsfortheAVD.Giveitaname,aplatformtarget,anSDcardsize,andaskin(HVGAisdefault).
4.Click
CreateAVD.
5.SelectthenewAVDfromthe
Start.
6.Aftertheemulatorbootsup,unlocktheemulatorscreen.
fromthetoolbar.EclipseinstallstheapponyourAVDandstartsit.
Ortorunyourappfromthecommandline:
1.ChangedirectoriestotherootofyourAndroidprojectandexecute:
2.MakesuretheAndroidSDK
3.Ontheemulator,locate
showyoubuildandrunyourAndroidappontheemulator!
BuildingaSimpleUserInterface
AlternativeLayouts
DeclaringyourUIlayoutinXMLratherthanruntimecodeisusefulforseveralreasons,butit'
sespeciallyimportantsoyoucancreatedifferentlayoutsfordifferentscreensizes.Forexample,youcancreatetwoversionsofalayoutandtellthesystemtouseoneon"
small"
screensandtheotheron"
large"
screens.Formoreinformation,seetheclassabout
SupportingDifferentDevices.
ThegraphicaluserinterfaceforanAndroidappisbuiltusingahierarchyof
View
and
ViewGroup
objects.
objectsareusuallyUIwidgetssuchas
buttons
or
textfields
andViewGroup
objectsareinvisibleviewcontainersthatdefinehowthechildviewsarelaidout,suchasinagridoraverticallist.
AndroidprovidesanXMLvocabularythatcorrespondstothesubclassesof
soyoucandefineyourUIinXMLusingahierarchyofUIelements.
Illustrationofhow
objectsformbranchesinthelayoutandcontainother
objects.
Inthislesson,you'
llcreatealayoutinXMLthatincludesatextfieldandabutton.Int