Hello, Android(安卓)深入(二)
ActivitiesandtheActivityLifecycle
-活动和活动生命周期
TheActivityclasscontainsthecodethatpowerstheuserinterface.TheActivityisresponsiblefor
respondingtouserinteractionandcreatingadynamicuserexperience.
活动类包含操纵用户界面的代码,活动负责响应用户交互并创建动态的用户体验。
InthissectionweintroducetheActivityclass,discusstheActivityLifecycle,anddissectthecode
thatpowerstheuserinterfaceinourPhonewordapplication.
本节介绍活动类,讨论活动的生命周期,并仔细分析在Phoneword应用中操纵用户界面的代码。
ActivityClass-活动类
OurPhonewordapplicationhasonlyonescreen(Activity).Theclassthatpowersthescreeniscalled
MainActivityandlivesintheMainActivity.csfile.ThenameMainActivityhasnospecialsignificance
inAndroid-althoughit’sconventiontonamethefirstActivityinanapplication"MainActivity",
Androidwouldn’tcareifwenameditsomethingelse.
我们的Phoneword应用只有一个屏显(活动)。操控这一屏显的类被称为MainActivity并且存在于MainActiviey.cs文件中。命名“MainActiviey”在安卓中没有特别的意义-尽管在一个应用中命名第一个活动为“MainActiviey”是一个惯例,如果我们命名为其它别的,安卓也不会介意。
IfweopentheMainActivity.csfile,weseethatourMainActivityclassisasubclassoftheActivityclass,
andthattheActivityisadornedwiththeActivityAttribute:
如果打开MainActivity.cs文件,会看到MainActivity类是一个Activity类的子类,而且该Activity被Activity属性修饰。
[Activity(Label="Phoneword",MainLauncher=true,Icon="@drawable/icon")]
publicclassMainActivity:Activity{...}
TheActivityAttributeregisterstheActivitywiththeAndroidManifest,lettingAndroidknowthatthisclassis
partofthePhonewordapplicationmanagedbythisManifest.TheLabelpropertysetsthetexttodisplay
atthetopofthescreen,andtheIconsetstheimagetodisplaynexttothetext,asillustratedbythe
screenshotbelow:
该Activity属性随着AndroidManifest注册了该Activity,让安卓知道这一类是被Manifest管理的Phoneword应用的一部分。Label属性设置在屏幕顶部显示的文本,Icon设置显示在文本之前的图像,如下图所示:
TheMainLauncherpropertytellsAndroidtodisplaythisActivitywhentheapplicationstartsup.This
propertybecomesimportantasweaddmoreActivities(screens)toourapplicationinthe
Hello,AndroidMultiscreenguide.
MainLauncher属性告诉安卓当应用启动时显示该活动。当我们按Hello,AndroidMultiscreen指南在应用中增加更多的活动(屏)时,该属性变得很重要。
NowthatweunderstandthebasicsoftheMainActivity,let’sdivedeeperintotheActivitycodeby
introducingtheActivitylifecycle.
刚才我们理解了MainActivity的基础知识,现在让我们通过介绍活动生命周更进一步深入到活动代码中,
ActivityLifecycle-活动生命周期
InAndroid,Activitiesgothroughdifferentstagesofalifecycledependingontheirinteractionswiththe
user.Activitiescanbecreated,startedandpaused,resumedanddestroyed,andsoon.TheActivity
classcontainsmethodsthatthesystemcallsatcertainpointsinthescreen'slifecycle.Thefollowing
diagramillustratesatypicallifeofanActivity,andsomeofthecorrespondinglifecyclemethods:
在Android,活动依赖与用户的交互,会经历一个生命周期的不同阶段,活动会被创建、开始、暂停、恢复、销毁,诸如此类。活动类包括方法,系统在屏显的生命周期的特定的点调用这些方法,下面的图表说明一个活动的典型生命,以及一些对应的生命周期方法:
ByoverridingActivitylifecyclemethods,wecancontrolhowtheActivityloads,howitreactstothe
user,andevenwhathappensafteritdisappearsfromthedevicescreen.Forexample,wecan
overridethelifecyclemethodsinthediagramabovetoperformsomeimportanttasks:
通过重载活动生命周期,我们可以控制活动如何装载、如何对用户做出反应、以及甚至其出现在设备屏幕上的发生什么。比如,我们可以重载上图中的生命周期方法来执行一些重要的任务:
·OnCreate–Createviews,initializevariables,anddootherprepworkbeforetheuserseesthe
Activity.ThismethodiscalledonlyoncewhentheActivityisloadedintomemory.
创建视图、初始化变量、在用户看见活动之前做其他的准备工作,这个方法只有当活动被装载入内存时都会被调用一次。
·
·OnResume–PerformanytasksthatneedtohappeneverytimetheActivityreturnstothedevicescreen.
执行任何时候活动返回设备屏幕时需要发生的一切任务。
·
·OnPause–PerformanytasksthatneedtohappeneverytimetheActivityleavesthedevicescreen.
执行任何时候活动离开设备屏幕时需要发生的一切任何。
WhenweaddcustomcodetoalifecyclemethodintheActivity,weoverridethatlifecyclemethod’sbaseimplementation.Wetapintotheexistinglifecyclemethod,whichhassomecodealreadyattached
toit,andweextenditwithourowncode.Wecallthebaseimplementationfrominsideourmethodto
makesuretheoriginalcoderunsbeforeournewcode.We’llseeanexampleofthisinthenextsection.
当我们增加自定义的代码到活动的生命周期方法时,我们重载那个生命周期方法的base实现。我们利用已存在的生命周期方法,该方法已经有一些代码存在,我们用自己的代码扩展它。我们从方法里调出base实现来确保原始代码在我们的新代码之前执行。我们将在后面的章节中看一个例子。
TheActivityLifecycleisanimportantandcomplexpartofAndroid,andwe’renotgoingtodiveintothe
detailsjustyet.Ifyou’dliketolearnmoreaboutActivitiesafteryoufinishtheGettingStartedseries,we
recommendreading
theActivityLifecycleguide.Fornow,let’sfocusonthefirststageoftheActivityLifecycle,OnCreate.
活动生命周期是Android中一个重要而复杂的部分,我们现在将不会深入到其细节。在学完本《开始》系统教程后,如果你喜欢学习更多活动的知识,我们建议你阅读活动生命周期指南。现在,我们聚集于活动生命周期的第一个阶段,OnCreate。
OnCreate
AndroidcallstheActivity’sOnCreatemethodwhenitcreatestheActivity,beforethescreenispresented
totheuser.WecanoverridetheOnCreatelifecyclemethodtocreateviewsandprepareourActivityto
meettheuser:
Android在创建一个活动时调用该活动的OnCreate方法,此时屏显还没有展现给用户。我们可以重载OnCreate生命周期方法来创建视图并准备我们的活动与用户见面。
protectedoverridevoidOnCreate(Bundlebundle)
{base.OnCreate(bundle);
//Setourviewfromthe"main"layoutresource
SetContentView(Resource.Layout.Main);
//Additionalsetupcodewillgohere}
InourPhonewordapp,thefirstthingwedoinOnCreateisloadtheuserinterfacewecreatedinthe
Androiddesigner.ToloadtheUI,wecallSetContentViewandpassittheresourcelayoutnamefor
thelayoutfile-ourMain.axml.OurlayoutislocatedatResource.Layout.Main:
在我们的Phonewordapp中,我们在OnCreate中所做的第一件事是装载我们在Android设计器中创建的用户界面。要载UI,我们调用SetContentView并给它传递我们的布局文件Main.axml的资源布局名称。我们的布局被定位在Resource.Layout.Main:
SetContentView(Resource.Layout.Main);
WhentheMainActivitystartsup,itwillcreateaviewbasedonthecontentsoftheMain.axmlfile.
Notethatwe’vematchedourlayoutnamewithourActivityname-Main.axmlisthelayoutfor
MainActivity.Thisisn’trequiredfromAndroid’spointofview,butaswebegintoaddmorescreens
totheapplication,we’llfindthisnamingconventionmakesiteasyforustomatchthecodefileto
thelayoutfile.
当MainActivity启动时,Android将创建一个基于Main.axml文件的内容的视图。注意我们已将布局名和活动名进行了一定的匹配-Main.axml是MainActivity的布局。从Android的观点来说,这是不必要的。但由于我们开始要增加更多的屏显到应用中,我们发现这种命名习惯使我们更易于将根据代码文找到相应的布局文件。
Oncethelayoutfileisset,wecanstartlookingupourcontrols.Tolookupacontrol,wecall
FindViewByIdandpassintheresourceIDofthecontrol:
一旦布局被设置好,我们就能开始查找我们的控件了,要查找控件,可调用FindViewById并将控件的资源ID传递给它。
EditTextphoneNumberText=FindViewById<EditText>(Resource.Id.PhoneNumberText);
ButtontranslateButton=FindViewById<Button>(Resource.Id.TranslateButton);
ButtoncallButton=FindViewById<Button>(Resource.Id.CallButton);
Nowthatwehaveareferencetothecontrolsinthelayoutfile,wecanstartprogrammingthemto
respondtouserinteraction.
现在,我们对Layout文件中的控件有了一个了解,我们可以开始对它们进行编程来响应用户的互动了。
RespondingtoUserInteraction
-响应用户互动
InAndroid,theClickeventlistensfortheuser’stouch.Inourapp,wehandledtheClickeventwithalambda,butwecouldhavealsousedadelegate
oranamedeventhandler.OurfinalTranslateButtoncoderesembledthefollowing:
在Android中,Click事件监听用户的触摸,在我们的应用中,我们用一个lambda来处理Click事件,但我们也可以使用委托或命名的事件处理程序。我们最后的TranslateButton代码类似如下:
translateButton.Click+=(objectsender,EventArgse)=>
{//Translateuser’salphanumericphonenumbertonumeric
translatedNumber=Core.PhonewordTranslator.ToNumber(phoneNumberText.Text);
if(String.IsNullOrWhiteSpace(translatedNumber))
{
callButton.Text="Call";
callButton.Enabled=false;
}
else
{
callButton.Text="Call"+translatedNumber;
callButton.Enabled=true;
}
};
AdditionalConceptsIntroducedinPhoneword
-Phoneword中介绍的附加概念
ThePhonewordapplicationintroducedseveralconceptsnotcoveredinthisguide.Theseconcepts
include:
Phoneword应用介绍了几个概念,在本指南中没有提到,他们包括:
·
ChangeButtonText–WelearnedtochangethetextofaButtonbyeditingthatButton’sTextproperty.Forexample,thefollowingcodechangesthecallButton’stextto"Call":
改变按钮文本-我们学习了通过编辑按钮的文本属性改变按钮的文本,比如,下列代码改变CallButton的文本为“Call”:
·
callButton.Text="Call";
·
·
EnableandDisableButtons–ButtonscanbeinanEnabledorDisabledstate.AdisabledButton
won’trespondtouserinput.Forexample,thefollowingcodedisablesthecallButton:
使按钮有效或无效-按钮可在有效或无效状态,无效的按钮将不会响应用户的输入。比如,下面的代码使callButton按钮无效:
·
callButton.Enabled=false;
·
Formoreinformationonbuttons,refertotheAndroidButtonsguide.
更多按钮的信息,参见Android按钮指南。
·
DisplayanAlertDialog–WhentheuserpressestheCallButton,ourappshowsanAlertDialog
withtheoptiontoplaceorcancelacall.TocreateanAlertDialog,weusedanAlertDialogBuilder.
OurdialogconsistsofaNeutralbuttontoplaceacallandaNegativebuttontocancelsthecall,as
illustratedbythecodebelow:
显示一个警示对话框-当用户按Callbutton,应用程序显示一个拨打或取消电话的警示对话框。要创建一个警示对话框,可使用一个AlertDialogBuilder。对话框包括一个中立的按钮来拨打电话,一个否定的按钮来取消电话,用以下代码说明:
·
varcallDialog=newAlertDialog.Builder(this);
callDialog.SetMessage("Call"+translatedNumber+"?");
callDialog.SetNeutralButton("Call",
Delegate
{//Createintenttodialphone
});
callDialog.SetNegativeButton("Cancel",delegate{});
//Showthealertdialogtotheuserandwaitforresponse.
callDialog.Show();
·
·
LaunchPhoneAppwithIntent–WhenwewireduptheCallButton,wesentanIntenttolaunch
thesystemphoneapp,passinginthetelephonenumberwewantedtocall,asillustratedbythe
codesamplebelow:
用意图开动手机应用-当我们按下CallButton,我们发送了一个意图来开动这个系统手机应用,将我们想要打的电话号码传进去,如以下代码所示:
·
varcallIntent=newIntent(Intent.ActionCall);
callIntent.SetData(Android.Net.Uri.Parse("tel:"+translatedNumber));
StartActivity(callIntent);
·
IntentsarecoveredinmoredepthintheHello,AndroidMultiscreenguide.Inthatguide,we’lllearntouseIntentstolaunchotherActivities(screens)andevenotherapplications.
意图(Intents)在Hello,AndroidMultiscreen指南中有更深的讨论,在那里,我们将学习使用意图开动其他的活动(屏显)甚至其他应用。
·
Testing,Deployment,andFinishingTouches
-测试、部署和收尾
BothXamarinStudioandVisualStudioprovidemanyoptionsfortestinganddeployinganapplication.
Thissectioncoversdebuggingoptions,demonstratestestingapplicationsondevice,andintroduces
toolsforcreatingcustomappiconsfordifferentscreendensities.
XamarinStudio和VisualStudio都提供许多方法来测试和部署应用。本节讨论调试方法、演示在设备上测试应用并介绍为不同的屏幕密度创建自定义app图标的工具。
DebuggingTools
Sometimesissuesinapplicationcodearedifficulttodiagnose.Tohelpdiagnosecomplexcodeissues,
wecouldSetaBreakpoint,StepThroughCode,orOutputInformationtotheLogWindow.
有时候应用代码中的问题很难判断。为了帮助判断复杂地代码问题,我们可以通Seta设置断点,步进代码或输出信息到日志窗口。
DeploytoaDevice--部署到设备
Theemulatorisagoodstartfordeployingandtestinganapplication,butuserswillnotconsumethe
finalappintheemulator.Weshouldtestapplicationsonarealdeviceearlyandoften.
模拟器是部署和测试应用的很好开端,但用户不会在模拟器上消费应用,我们应该及早并经常在真实的设备上测试应用。
BeforeanAndroiddevicecanbeusedfortestingapplications,itneedstobeconfiguredfordevelopment.
TheSetUpDeviceforDevelopmentguideprovidesthoroughinstructionsongettingadevicereadyfor
development.
Oncethedeviceisconfigured,wecandeploytoitbypluggingitin,selectingitfromtheSelectDevicedialog,
andstartingtheapplication:
一个Android设备能被用于测试应用前,它需要为开发被配置。为开发设置设备指南提供了使设备为开发作好准备的全面说明。
Thiswilllaunchtheapplicationonthedevice:
这将在设备上开动应用。
SetIconsforDifferentScreenDensities
-为不同的屏幕密度设置图标
Androiddevicescomeindifferentscreensizesandresolutions,andnotallimageslookgoodonall
screens.Forexample,hereisascreenshotofalow-densityicononahigh-densityNexus5.Noticehowblurryitiscomparedtothesurroundingicons:
安卓设备会有不同的屏幕尺寸和分辨率,不是所有的图像在所有的屏幕上都好看。比如,这是一个低密图标在高密Nexus5上的屏幕截图,可以看到和周围的其他图标相比,这个图标非常模糊。
Toaccountforthis,itisgoodpracticetoaddiconsofdifferentresolutionstotheResourcesfolder.
Androidprovidesdifferentversionsofthedrawablefoldertohandleimagesofdifferentdensities,
includinganldpiversionforlowdensity,mdpiformedium,hdpiforhigh,andxhdpiandxxhdpifor
veryhighdensityscreens.Iconsofvaryingsizesarestoredintheappropriatedrawable-*folders:
为了解释这个,把不同分辨率的图标加入到Resources文件夹中是一个好的办法。安卓提供不同版本的绘图文件夹来处理不同密度的图像,包括ldpi版对应底密度、mdpi对应中密度、hdpi对应高,xhdpi和xxhdpi对应非常高的屏幕密度。不同尺寸的图标被存储在适当的drawable-*文件夹中。
Androidwillpicktheiconwiththeappropriatedensity:
安卓将排行合适密度的图标。
GenerateCustomIcons
制作自定义图标
Noteveryonehasadesigneravailabletocreatethecustomiconsandlaunchimagesanappneeds
tostandout.Hereareseveralalternateapproachestogeneratingcustomappartwork:
非常所有的人都有可用的设计器来创建自定义图标并生成使应用显得突出的图像。这些有几个适当方法来制作自定义app图像。
·AndroidAssetStudio–Aweb-based,in-browsergeneratorforalltypesofAndroidicons,withlinkstootherusefulcommunitytools.ItworksbestinGoogleChrome.
·AndroidAssetStudio-一个基于网页、在线生成所有类型安卓图标随带链接到其他有用社区的工具,可在GoogleChrome中良好运行。
·VisualStudio–YoucanusethistocreateasimpleiconsetforyourappdirectlyintheIDE.
·VisualStudio-你可以使用这个来创建一个简单的图标集直接在IDE中用于你的app。
·Glyphish–High-qualityprebuilticonsetsforfreedownloadandpurchase.
·Glyphish-高品质重建图标套件,可自由下载和购买。
·Fivrr–Choosefromavarietyofdesignerstocreateaniconsetforyou,startingat$5.Canbehitor
missbutagoodresourceifyouneediconsdesignedonthefly.
·Fivrr--选择设计者为您创建一套图标,5元起价,无论如何,当你急着需要图标时,这是一个好的资源。
Formoreinformationabouticonsizesandrequirements,refertotheAndroidResourcesguide.
更多图标尺寸和需求的信息,参见AndroidResources指南。
Summary-总结
Congratulations!YounowhaveasolidunderstandingofthecomponentsofaXamarin.Androidapplication
aswellasthetoolsrequiredtocreateit.
祝贺你。现在你已经对Xamarin.Android应用的各部分以及需要用于创建Xamarin.Android应用的工具有了一个可靠的理解。
InthenexttutorialintheGettingStartedseries,we'llextendourapplicationtohandlemultiplescreensas
weexploremoreadvancedAndroidarchitectureandconcepts.
在GettingStarted系列的下一个教程,我们将将应用扩展到操控多个屏显以探究更多高级的安卓体系结构和概念。
更多相关文章
- 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
- android 源代码版本号整理
- Android获取当前进程名
- Android(安卓)生命周期架构组件使用方法
- android 如何判断开机完成
- Android获取屏幕大小 .
- Android(安卓)Activity 半透明效果(Translucent)
- Android(安卓)OpenGL学习笔记(二)之----三角形的绘制.
- android binder 机制三(匿名Service)