构建你的第一个Android应用程序.docx

上传人:b****4 文档编号:4026246 上传时间:2022-11-27 格式:DOCX 页数:11 大小:176.07KB
下载 相关 举报
构建你的第一个Android应用程序.docx_第1页
第1页 / 共11页
构建你的第一个Android应用程序.docx_第2页
第2页 / 共11页
构建你的第一个Android应用程序.docx_第3页
第3页 / 共11页
构建你的第一个Android应用程序.docx_第4页
第4页 / 共11页
构建你的第一个Android应用程序.docx_第5页
第5页 / 共11页
点击查看更多>>
下载资源
资源描述

构建你的第一个Android应用程序.docx

《构建你的第一个Android应用程序.docx》由会员分享,可在线阅读,更多相关《构建你的第一个Android应用程序.docx(11页珍藏版)》请在冰豆网上搜索。

构建你的第一个Android应用程序.docx

构建你的第一个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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 农林牧渔 > 林学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1