Android起航 毕业论文外文翻译

Android起航 毕业论文外文翻译

ID:240251

大小:750.33 KB

页数:32页

时间:2017-07-12

上传者:green wind
Android起航  毕业论文外文翻译_第1页
Android起航  毕业论文外文翻译_第2页
Android起航  毕业论文外文翻译_第3页
Android起航  毕业论文外文翻译_第4页
Android起航  毕业论文外文翻译_第5页
资源描述:

《Android起航 毕业论文外文翻译》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库

外文原文BeginningAndroidMarkL.MurphywriteUsingXML-BasedLayoutsWhileitistechnicallypossibletocreateandattachwidgetstoouractivitypurelythroughJavacode,thewaywedidinChapter4,themorecommonapproachistouseanXML-basedlayoutfile.Dynamicinstantiationofwidgetsisreservedformorecomplicatedscenarios,wherethewidgetsarenotknownatcompile-time(eg.,populatingacolumnofradiobuttonsbasedondataretrievedofftheInternet).Withthatinmind,it’stimetobreakouttheXMLandlearnhowtolayoutAndroidactivitiesthatway.WhatIsanXML-BasedLayout?Asthenamesuggests,anXML-basedlayoutisaspecificationofwidgets’relationshipstoeachother—andtotheircontainers(moreonthisinChapter7)—encodedinXMLformat.Specifically,AndroidconsidersXML-basedlayoutstoberesources,andassuchlayoutfilesarestoredintheres/layoutdirectoryinsideyourAndroidproject.EachXMLfilecontainsatreeofelementsspecifyingalayoutofwidgetsandtheircontainersthatmakeuponeviewhierarchy.TheattributesoftheXMLelementsareproperties,describinghowawidgetshouldlookorhowacontainershouldbehave.Forexample,ifaButtonelementhasanattributevalueofandroid:textStyle="bold",thatmeansthatthetextappearingonthefaceofthebuttonshouldberenderedinaboldfacefontstyle.Android’sSDKshipswithatool(aapt)whichusesthelayouts.ThistoolshouldbeautomaticallyinvokedbyyourAndroidtoolchain(e.g.,Eclipse,Ant’sbuild.xml).OfparticularimportancetoyouasadeveloperisthataaptgeneratestheR.javasourcefilewithinyourproject,allowingyoutoaccesslayoutsand widgetswithinthoselayoutsdirectlyfromyourJavacode.WhyUseXML-BasedLayouts?MosteverythingyoudousingXMLlayoutfilescanbeachievedthroughJavacode.Forexample,youcouldusesetTypeface()tohaveabuttonrenderitstextinbold,insteadofusingapropertyinanXMLlayout.SinceXMLlayoutsareyetanotherfileforyoutokeeptrackof,weneedgoodreasonsforusingsuchfiles.Perhapsthebiggestreasonistoassistinthecreationoftoolsforviewdefinition,suchasaGUIbuilderinanIDElikeEclipseoradedicatedAndroidGUIdesignerlikeDroidDraw1.SuchGUIbuilderscould,inprinciple,generateJavacodeinsteadofXML.Thechallengeisre-readingtheUIdefinitiontosupportedits—thatisfarsimplerifthedataisinastructuredformatlikeXMLthaninaprogramminglanguage.Moreover,keepinggeneratedXMLdefinitionsseparatedfromhand-writtenJavacodemakesitlesslikelythatsomebody’scustom-craftedsourcewillgetclobberedbyaccidentwhenthegeneratedbitsgetre-generated.XMLformsanicemiddlegroundbetweensomethingthatiseasyfortool-writerstouseandeasyforprogrammerstoworkwithbyhandasneeded.Also,XMLasaGUIdefinitionformatisbecomingmorecommonplace.Microsoft’sXAML2,Adobe’sFlex3,andMozilla’sXUL4alltakeasimilarapproachtothatofAndroid:putlayoutdetailsinanXMLfileandputprogrammingsmartsinsourcefiles(e.g.,JavaScriptforXUL).Manyless-well-knownGUIframeworks,suchasZK5,alsouseXMLforviewdefinition.While“followingtheherd”isnotnecessarilythebestpolicy,itdoeshavetheadvantageofhelpingtoeasethetransitionintoAndroidfromanyotherXML-centeredviewdescriptionlanguage.OK,SoWhatDoesItLookLike?HereistheButtonfromthepreviouschapter’ssampleapplication,convertedintoanXMLlayoutfile,foundintheLayouts/NowReduxsampleproject.ThiscodesamplealongwithallothersinthischaptercanbefoundintheSourceCodeareaofhttp://apress.com. Theclassnameofthewidget—Button—formsthenameoftheXMLelement.SinceButtonisanAndroid-suppliedwidget,wecanjustusethebareclassname.Ifyoucreateyourownwidgetsassubclassesofandroid.view.View,youwouldneedtoprovideafullpackagedeclarationaswell.TherootelementneedstodeclaretheAndroidXMLnamespace:xmlns:android="http://schemas.android.com/apk/res/android"Allotherelementswillbechildrenoftherootandwillinheritthatnamespacedeclaration.BecausewewanttoreferencethisbuttonfromourJavacode,weneedtogiveitanidentifierviatheandroid:idattribute.Wewillcoverthisconceptingreaterdetaillaterinthischapter.TheremainingattributesarepropertiesofthisButtoninstance:•android:textindicatestheinitialtexttobedisplayedonthebuttonface(inthiscase,anemptystring)•android:layout_widthandandroid:layout_heighttellAndroidtohavethebutton’swidthandheightfillthe“parent”,inthiscasetheentirescreen—theseattributeswillbecoveredingreaterdetailinChapter7.Sincethissinglewidgetistheonlycontentinouractivity,weonlyneedthissingleelement.ComplexUIswillrequireawholetreeofelements,representingthewidgetsandcontainersthatcontroltheirpositioning.AlltheremainingchaptersofthisbookwillusetheXMLlayoutformwheneverpractical,sotherearedozensofotherexamplesofmorecomplexlayoutsforyoutoperusefromChapter7onward.What’swiththe@Signs? ManywidgetsandcontainersonlyneedtoappearintheXMLlayoutfileanddonotneedtobereferencedinyourJavacode.Forexample,astaticlabel(TextView)frequentlyonlyneedstobeinthelayoutfiletoindicatewhereitshouldappear.ThesesortsofelementsintheXMLfiledonotneedtohavetheandroid:idattributetogivethemaname.AnythingyoudowanttouseinyourJavasource,though,needsanandroid:id.Theconventionistouse@+id/...astheidvalue,wherethe...representsyourlocallyuniquenameforthewidgetinquestion.IntheXMLlayoutexampleintheprecedingsection,@+id/buttonistheidentifierfortheButtonwidget.Androidprovidesafewspecialandroid:idvalues,oftheform@android:id/....Wewillseesomeoftheseinvariouschaptersofthisbook,suchasChapters8and10.WeAttachThesetotheJavaHow?GiventhatyouhavepainstakinglysetupthewidgetsandcontainersinanXMLlayoutfilenamedmain.xmlstoredinres/layout,allyouneedisonestatementinyouractivity’sonCreate()callbacktousethatlayout:setContentView(R.layout.main);ThisisthesamesetContentView()weusedearlier,passingitaninstanceofaViewsubclass(inthatcase,aButton).TheAndroid-builtview,constructedfromourlayout,isaccessedfromthatcode-generatedRclass.AllofthelayoutsareaccessibleunderR.layout,keyedbythebasenameofthelayoutfile—main.xmlresultsinR.layout.main.Toaccessouridentifiedwidgets,usefindViewById(),passinginthenumericidentifierofthewidgetinquestion.ThatnumericidentifierwasgeneratedbyAndroidintheRclassasR.id.something(wheresomethingisthespecificwidgetyouareseeking).ThosewidgetsaresimplysubclassesofView,justliketheButtoninstancewecreatedinChapter4. TheRestoftheStoryIntheoriginalNowdemo,thebutton’sfacewouldshowthecurrenttime,whichwouldreflectwhenthebuttonwaslastpushed(orwhentheactivitywasfirstshown,ifthebuttonhadnotyetbeenpushed).Mostofthatlogicstillworks,eveninthisreviseddemo(NowRedux).However,ratherthaninstantiatingtheButtoninouractivity’sonCreate()callback,wecanreferencetheonefromtheXMLlayout:packagecom.commonsware.android.layouts;importandroid.app.Activity;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.Button;importjava.util.Date;publicclassNowReduxextendsActivityimplementsView.OnClickListener{Buttonbtn;@OverridepublicvoidonCreate(Bundleicicle){super.onCreate(icicle);setContentView(R.layout.main);btn=(Button)findViewById(R.id.button);btn.setOnClickListener(this);updateTime();}publicvoidonClick(Viewview){updateTime();}privatevoidupdateTime(){btn.setText(newDate().toString());}}ThefirstdifferenceisthatratherthansettingthecontentviewtobeaviewwecreatedinJavacode,wesetittoreferencetheXMLlayout(setContentView(R.layout.main)).TheR.javasourcefilewillbeupdatedwhenwerebuildthisprojecttoincludeareferencetoourlayoutfile(storedasmain.xmlinourproject’sres/layoutdirectory).TheotherdifferenceisthatweneedtogetourhandsonourButtoninstance, forwhichweusethefindViewById()call.Sinceweidentifiedourbuttonas@+id/button,wecanreferencethebutton’sidentifierasR.id.button.Now,withtheButtoninstanceinhand,wecansetthecallbackandsetthelabelasneeded.AsyoucanseeinFigure5-1,theresultslookthesameaswiththeoriginalNowdemo.Figure5-1.TheNowReduxsampleactivityEmployingBasicWidgetsEveryGUItoolkithassomebasicwidgets:fields,labels,buttons,etc.Android’stoolkitisnodifferentinscope,andthebasicwidgetswillprovideagoodintroductionastohowwidgetsworkinAndroidactivities.AssigningLabelsThesimplestwidgetisthelabel,referredtoinAndroidasaTextView.Likein mostGUItoolkits,labelsarebitsoftextnoteditabledirectlybyusers.Typically,theyareusedtoidentifyadjacentwidgets(e.g.,a“Name:”labelbeforeafieldwhereonefillsinaname).InJava,youcancreatealabelbycreatingaTextViewinstance.Morecommonly,though,youwillcreatelabelsinXMLlayoutfilesbyaddingaTextViewelementtothelayout,withanandroid:textpropertytosetthevalueofthelabelitself.Ifyouneedtoswaplabelsbasedoncertaincriteria,suchasinternationalization,youmaywishtousearesourcereferenceintheXMLinstead,aswillbedescribedinChapter9.TextViewhasnumerousotherpropertiesofrelevanceforlabels,suchas:•android:typefacetosetthetypefacetouseforthelabel(e.g.,monospace)•android:textStyletoindicatethatthetypefaceshouldbemadebold(bold),italic(italic),orboldanditalic(bold_italic)•android:textColortosetthecolorofthelabel’stext,inRGBhexformat(e.g.,#FF0000forred)Forexample,intheBasic/Labelproject,youwillfindthefollowinglayoutfile:AsyoucanseeinFigure6-1,justthatlayoutalone,withthestubJavasourceprovidedbyAndroid’sprojectbuilder(e.g.,activityCreator),givesyoutheapplication. Figure6-1.TheLabelDemosampleapplicationButton,Button,Who’sGottheButton?We’vealreadyseentheuseoftheButtonwidgetinChapters4and5.Asitturnsout,ButtonisasubclassofTextView,soeverythingdiscussedintheprecedingsectionintermsofformattingthefaceofthebuttonstillholds.FleetingImagesAndroidhastwowidgetstohelpyouembedimagesinyouractivities:ImageViewandImageButton.Asthenamessuggest,theyareimage-basedanaloguestoTextViewandButton,respectively.Eachwidgettakesanandroid:srcattribute(inanXMLlayout)tospecifywhatpicturetouse.Theseusuallyreferenceadrawableresource,describedingreaterdetailinthechapteronresources.YoucanalsosettheimagecontentbasedonaUrifromacontentproviderviasetImageURI().ImageButton,asubclassofImageView,mixesinthestandardButtonbehaviors,forrespondingtoclicksandwhatnot.Forexample,takeapeekatthemain.xmllayoutfromtheBasic/ImageViewsampleprojectwhichisfoundalongwithallothercodesamplesathttp://apress.com:Theresult,justusingthecode-generatedactivity,isshowninFigure6-2.Figure6-2.TheImageViewDemosampleapplicationFieldsofGreen.OrOtherColors.Alongwithbuttonsandlabels,fieldsarethethird“anchor”ofmostGUItoolkits.InAndroid,theyareimplementedviatheEditTextwidget,whichisasubclassoftheTextViewusedforlabels.AlongwiththestandardTextViewproperties(e.g.,android:textStyle),EditTexthasmanyothersthatwillbeusefulforyouinconstructingfields,including:•android:autoText,tocontrolifthefieldshouldprovideautomaticspellingassistance•android:capitalize,tocontrolifthefieldshouldautomaticallycapitalizethefirstletterofenteredtext(e.g.,firstname,city) •android:digits,toconfigurethefieldtoacceptonlycertaindigits•android:singleLine,tocontrolifthefieldisforsingle-lineinputormultiple-lineinput(e.g.,doesmoveyoutothenextwidgetoraddanewline?)Beyondthose,youcanconfigurefieldstousespecializedinputmethods,suchasandroid:numericfornumeric-onlyinput,android:passwordforshroudedpasswordinput,andandroid:phoneNumberforenteringinphonenumbers.Ifyouwanttocreateyourowninputmethodscheme(e.g.,postalcodes,SocialSecuritynumbers),youneedtocreateyourownimplementationoftheInputMethodinterface,thenconfigurethefieldtouseitviaandroid:inputMethod.Forexample,fromtheBasic/Fieldproject,hereisanXMLlayoutfileshowinganEditText:Notethatandroid:singleLineisfalse,souserswillbeabletoenterinseverallinesoftext.Forthisproject,theFieldDemo.javafilepopulatestheinputfieldwithsomeprose:packagecom.commonsware.android.basic;importandroid.app.Activity;importandroid.os.Bundle;importandroid.widget.EditText;publicclassFieldDemoextendsActivity{@OverridepublicvoidonCreate(Bundleicicle){super.onCreate(icicle);setContentView(R.layout.main); EditTextfld=(EditText)findViewById(R.id.field);fld.setText("LicensedundertheApacheLicense,Version2.0"+"(the"License");youmaynotusethisfile"+"exceptincompliancewiththeLicense.Youmay"+"obtainacopyoftheLicenseat"+"http://www.apache.org/licenses/LICENSE-2.0");}}Theresult,oncebuiltandinstalledintotheemulator,isshowninFigure6-3.Figure6-3.TheFieldDemosampleapplicationNoteAndroid’semulatoronlyallowsoneapplicationinthelauncherperuniqueJavapackage.Sinceallthedemosinthischaptersharethecom.commonsware.android.basicpackage,youwillonlyseeoneofthesedemosinyouremulator’slauncheratanyonetime.Anotherflavoroffieldisonethatoffersauto-completion,tohelpuserssupplyavaluewithouttypinginthewholetext.ThatisprovidedinAndroidastheAutoCompleteTextViewwidgetandisdiscussedinChapter8. JustAnotherBoxtoCheckTheclassiccheckboxhastwostates:checkedandunchecked.Clickingthecheckboxtogglesbetweenthosestatestoindicateachoice(e.g.,“Addrushdeliverytomyorder”).InAndroid,thereisaCheckBoxwidgettomeetthisneed.IthasTextViewasanancestor,soyoucanuseTextViewpropertieslikeandroid:textColortoformatthewidget.WithinJava,youcaninvoke:•isChecked()todetermineifthecheckboxhasbeenchecked•setChecked()toforcethecheckboxintoacheckedoruncheckedstate•toggle()totogglethecheckboxasiftheusercheckeditAlso,youcanregisteralistenerobject(inthiscase,aninstanceofOnCheckedChangeListener)tobenotifiedwhenthestateofthecheckboxchanges.Forexample,fromtheBasic/CheckBoxproject,hereisasimplecheckboxlayout:ThecorrespondingCheckBoxDemo.javaretrievesandconfiguresthebehaviorofthecheckbox:publicclassCheckBoxDemoextendsActivityimplementsCompoundButton.OnCheckedChangeListener{CheckBoxcb;@OverridepublicvoidonCreate(Bundleicicle){super.onCreate(icicle);setContentView(R.layout.main);cb=(CheckBox)findViewById(R.id.check);cb.setOnCheckedChangeListener(this);}publicvoidonCheckedChanged(CompoundButtonbuttonView,booleanisChecked){ if(isChecked){cb.setText("Thischeckboxis:checked");}else{cb.setText("Thischeckboxis:unchecked");}}}NotethattheactivityservesasitsownlistenerforcheckboxstatechangessinceitimplementstheOnCheckedChangeListenerinterface(viacb.setOnCheckedChangeListener(this)).ThecallbackforthelistenerisonCheckedChanged(),whichreceivesthecheckboxwhosestatehaschangedandwhatthenewstateis.Inthiscase,weupdatethetextofthecheckboxtoreflectwhattheactualboxcontains.Theresult?Clickingthecheckboximmediatelyupdatesitstext,asyoucanseeinFigures6-4and6-5.Figure6-4.TheCheckBoxDemosampleapplication,withthecheckboxunchecked Figure6-5.Thesameapplication,nowwiththecheckboxcheckedTurntheRadioUpAswithotherimplementationsofradiobuttonsinothertoolkits,Android’sradiobuttonsaretwo-state,likecheckboxes,butcanbegroupedsuchthatonlyoneradiobuttoninthegroupcanbecheckedatanytime.LikeCheckBox,RadioButtoninheritsfromCompoundButton,whichinturninheritsfromTextView.Hence,allthestandardTextViewpropertiesforfontface,style,color,etc.,areavailableforcontrollingthelookofradiobuttons.Similarly,youcancallisChecked()onaRadioButtontoseeifitisselected,toggle()toselectit,andsoon,likeyoucanwithaCheckBox.Mosttimes,youwillwanttoputyourRadioButtonwidgetsinsideofaRadioGroup.TheRadioGroupindicatesasetofradiobuttonswhosestateistied,meaningonlyonebuttonoutofthegroupcanbeselectedatanytime.Ifyouassignanandroid:idtoyourRadioGroupinyourXMLlayout,youcanaccessthegroupfromyourJavacodeandinvoke:•check()tocheckaspecificradiobuttonviaitsID(e.g.,group.check(R.id.radio1))•clearCheck()toclearallradiobuttons,sononeinthegrouparechecked•getCheckedRadioButtonId()togettheIDofthecurrently-checkedradio button(or-1ifnonearechecked)Forexample,fromtheBasic/RadioButtonsampleapplication,hereisanXMLlayoutshowingaRadioGroupwrappingasetofRadioButtonwidgets:Figure6-6showstheresultusingthestockAndroid-generatedJavafortheprojectandthislayout. Figure6-6.TheRadioButtonDemosampleapplicationNotethattheradiobuttongroupisinitiallysettobecompletelyuncheckedattheoutset.Topre-setoneoftheradiobuttonstobechecked,useeithersetChecked()ontheRadioButtonorcheck()ontheRadioGroupfromwithinyouronCreate()callbackinyouractivity.It’sQuiteaViewAllwidgets,includingtheonespreviouslyshown,extendView,andassuchgiveallwidgetsanarrayofusefulpropertiesandmethodsbeyondthosealreadydescribed.UsefulPropertiesSomeofthepropertiesonViewmostlikelytobeusedinclude:•Controlsthefocussequence:•android:nextFocusDown•android:nextFocusLeft•android:nextFocusRight•android:nextFocusUp•android:visibility,whichcontrolswhetherthewidgetisinitiallyvisible•android:background,whichtypicallyprovidesanRGBcolorvalue(e.g., #00FF00forgreen)toserveasthebackgroundforthewidgetUsefulMethodsYoucantogglewhetherornotawidgetisenabledviasetEnabled()andseeifitisenabledviaisEnabled().OnecommonusepatternforthisistodisablesomewidgetsbasedonaCheckBoxorRadioButtonselection.YoucangiveawidgetfocusviarequestFocus()andseeifitisfocusedviaisFocused().Youmightusethisinconcertwithdisablingwidgetsaspreviouslymentioned,toensuretheproperwidgethasthefocusonceyourdisablingoperationiscomplete.Tohelpnavigatethetreeofwidgetsandcontainersthatmakeupanactivity’soverallview,youcanuse:•getParent()tofindtheparentwidgetorcontainer•findViewById()tofindachildwidgetwithacertainID•getRootView()togettherootofthetree(e.g.,whatyouprovidedtotheactivityviasetContentView())外文翻译Android起航译使用XML进行布局虽然纯粹通过Java代码在activity上创建和添加部件,在技术上是可行的,我们在第4章中做的一样,更常见的方法是使用一种基于XML的布局文件。动态的小部件实例保留更多,情况复杂,小工具在编译时不为人所知(例如,在数据检索了互联网基础上将单选按钮填充柱。 考虑到这一点,现在是时候打破XML来学习如何用此种方式来布置Androidactivities。什么是基于XML的布局?正如其名称所示,一个基于XML的布局是一个关系到每个规格的小部件,和他们的容器(更多关于此内容的在第7章)编码的XML格式。具体来说,Android认为基于XML的布局是资源,因此布局文件存储在res/在你的Android项目布局目录中。每个XML文件包含一个指定的部件和容器布局元素树,一种意见认为构成层次。对XML元素的属性,描述一个部件应如何看或者一个容器应如何运转。例如,如果一个按钮元素。有一个Android的属性值:文字样式=“bold”,这意味着该文本出现在按钮的表面应该是呈现一个粗体字体样式.Android的SDK中附带一个使用的布局的工具(aapt)。这个工具应自动调用你的Android工具链(例如,Eclipse中,Ant’sbuild.xml)。作为一个开发人员,尤其重要的是,在您的项目中aapt生成R.java源文件,让您能在那些布局中直接从Java代码中获取布局和部件。为什么使用基于XML的布局?使用XML布局文件做的大部分都可以通过Java代码。例如,你可以使用setTypeface()命令一个按钮使用粗体文本,而不是在一个XML布局中使用属性。由于XML布局是为你跟踪的另一个文件,所以我们需要好的理由来使用这样的文件。也许最大的原因是为了在视图定义中协助工具的建立,如IDE中一个GUI创建者像Eclipse或者一个像DroidDraw1设计GUI图形用户界面建设者。这样GUI建设者们,在原则上,生成Java代码而不是XML。目前的挑战是重新阅读用户界面的定义,以支持编辑,也就是说,如果是像XLM的结构公式数据比一个程序语言中的数据简单的多。此外,保持生成的XML定义从手写的Java代码中分离,使得某人定制的来源意外重新生成不太可能。XML形成一个良好的中间立场,使工具作家使用更简便,程序员需要时手工工作更简易。此外,XML作为一个GUI定义格式是越来越普遍。微软的XAML,Adobe的Flex, 和Mozilla的XUL都采取Android类似的方法:把布局细节放在一个XML文件和把编程智慧资料放在源文件(例如,XUL中的JavaScript)。许多不太知名的图形用户界面框架,如ZK,还使用视图定义的XML。而“随大流”并不一定是最好的政策,但他们有优势帮助从任何其他XML为中心的观点描述语言轻松进入Android。好了,那么基于XML的布局是什么样子的?下面是以前的章节的示例应用程序按钮,转换成一个XML布局文件,布局/NowRedux示例项目,在这一章中可以找到源代码的http://apress.com领域。部件,按钮的类名称形成XML元素的名称。因为按钮是Android提供的部件,我们可以只使用裸类的名称。如果您创建自己的部件作为android.view.View子小部件,您也将需要提供一个完整的包声明(如com.commonsware.android.MyWidget)。根元素需要Android的XML命名空间声明:xmlns:android="http://schemas.android.com/apk/res/android"所有其他要素将成为子根并继承该命名空间的声明。因为我们要引用这个来自Java代码的按钮,我们需要通过android给它一个标识符:id属性。我们将在本章后面更详细的介绍这个概念。其余的属性是此按钮实例属性:•android:文字表示的初始文本将显示在按钮(这种情况显示空字符串)•android:layout_width和Android:layout_height命令android有按钮的宽度和高度填写“parent”,这种情况下,整个屏幕。将这些属性将在第7章中详解。由于这个单一部件是activity的仅有内容,我们只需要这一个因素。复杂的用户界面将需要整个树的元素,代表工具和容器,控制自己的定位。所有的这本书余下的章节将使用XML布局,所以还有数十种更复杂的其他布局实例,请前进 到第七章仔细阅读。@符号有什么用途?许多部件和容器只需要出现在XML布局文件,不须引用在Java代码。例如,一个静态标签(TextView)只需要在布局文件中以表明它应该出现在那里。在XML文件中各种元素文件不需要有android:id属性给他们一个名称。任何你想要在Java资源中使用的东西,都需要一个android:id.该公约是使用@+id...作为ID值,其中的...代表你locallyunique名称有问题的部件。在上一节的XML布局的例子中,@+id是按钮控件的标识符。android提供了一些特殊的android:ID值,形式@android:id/...我们将在这本书的不同章节中看到这些,例如第八章和第十章。我们将这些附加到Java…如何?既然你有意建立一个XML配置文件的工具和容器,名为main.xml存储res/layout,所有你需要的是一个在您activity的OnCreate()回调以使用该版式:setContentView(R.layout.main);这是相同的setContentView(),我们前面使用,通过它的一个视图子类的实例(在这种情况下,一个按钮)。该android制造的观点,来自我们的布局,是从访问该代码生成的R类。所有的布局都可以访问R.layout,由基地键控布局文件的名称-main.xmlresultinR.layout.main.要访问确定部件,使用findViewById(),在数字标识符传递有问题的部件。这一数字标识符生成的R类由android在R.id.something(其中一些是你正在寻找的具体部件)。这些部件是只是子类的视图,就像我们在第四章中创建Button实例。剩下的部分在原始的Now演示中,按钮的表面便会显示当前的时间,这将反映当按钮被最后按下时显示的时间(或者如果在按钮尚未被按下时显示)。这种逻辑仍然适用,即使在该修订演示(NowRedux)中。尽管如此,在activity’sonCreate()callback中的实例,我们可以从XML的布局参考一个例子:packagecom.commonsware.android.layouts;importandroid.app.Activity; importandroid.os.Bundle;importandroid.view.View;importandroid.widget.Button;importjava.util.Date;publicclassNowReduxextendsActivityimplementsView.OnClickListener{Buttonbtn;@OverridepublicvoidonCreate(Bundleicicle){super.onCreate(icicle);setContentView(R.layout.main);btn=(Button)findViewById(R.id.button);btn.setOnClickListener(this);updateTime();}publicvoidonClick(Viewview){updateTime();}privatevoidupdateTime(){btn.setText(newDate().toString());}}第一个区别是,在Java代码中设置内容视图作为视图,我们将它设置为引用的XML布局(setContentView(R.layout.main))。该R.java源文件将被更新,当我们重建这个项目,包括对我们布局参考文件(存储在main.xmlinourproject’sres/layoutdirectory)。另一个不同是,我们需要亲手实验按钮实例,我们使用findViewById()调用。既然我们发现按钮为@+id/button,我们可以参考按钮的标识符R.id.button。现在,随着手手头上的实例,我们可以设置回调并根据需要设置标签。正如你可以看到如图5-1,结果看起来与原始的Now演示一样。 图5-1样本的NowRedux活动使用基本部件每一个GUI工具包都有一些基本的部件:字段,标签,按钮等,Android的工具包在范围内没有不同,其基本部件将提供一个良好的介绍,关于这些部件在Androidactivities中是如何运行的。指派标签最简单的部件是标签,在Android提到的作为一个TextView。像大多数的GUI工具包,标签的文本是不可被用户直接编辑的。通常情况下,它们被用来确定相邻部件(例如,一个“姓名:”一个填充姓名前的标签)。在Java中,你可以通过创建一个TextView的实例l来创建一个标签。更常见的,虽然,你将通过添加一个TextView元素到布局来在XML布局文件中创建标签,与一个Android:文本属性来设置标签的本身价值。如果您需要交换基于某些标准的标 签,例如国际化,你可能想使用XML中的资源参考代替,这些将在第9章叙述。TextView有许多相关的其他标签属性,如:•android:typefacetosetthetypefacetouseforthelabel(e.g.,monospace)•android:textStyletoindicatethatthetypefaceshouldbemadebold(bold),italic(italic),orboldanditalic(bold_italic)•android:textColortosetthecolorofthelabel’stext,inRGBhexformat(e.g.,#FF0000forred)例如,在Basic/Label项目中,你将找到下列布局文件:正如你看到的图6-1,图6-1示例应用程序的LabelDemo只是单独的布局,由android的项目生成器提供的Java源的(如 activityCreator),生成应用程序。按钮,归属于谁?我们已经在第4和第5章看到了按钮部件用法。按钮是文本视图的一个子类,所以一切都在上一节讨论了,按钮格式所面临的问题仍然成立。短暂的图像Android有两个部件,来帮助你将照片嵌入activities:ImageView和ImageButton。正如名称所暗示的,他们是分别对于文本视图和按钮基于图像的类似物。每个部件带有一个android:src属性(在一个XML布局中),指明使用什么图片。这些通常引用一个可绘制的资源,在讲资源的这个章节中更详细地描述了。您还可以通过setImageURI()从内容提供商在Uri基础上设置图像。ImageButton控件,一个ImageView子类,混合在标准按钮行为中,应对点击和诸如此类的东西。例如,从Basic/ImageView样本项目中看main.xml布局,这可以在http://apress.com以及所有其他代码示例种找到。结果,只用代码生成activity,如图6-2所示。 图6-2示例应用程序的ImageViewDemo绿色字段或者其他色彩紧接着按钮和标签,字段是大多数GUI工具包的第三个“锚”。在Android中,他们通过EditText部件运行,它是标签的一个子类TextView。随着标准TextView属性(例如,Android:文本样式),EditText有许多其他方面可以帮助你创建字段,包括:•android:autoText,tocontrolifthefieldshouldprovideautomaticspellingassistance•android:capitalize,tocontrolifthefieldshouldautomaticallycapitalizethefirstletterofenteredtext(e.g.,firstname,city)•android:digits,toconfigurethefieldtoacceptonlycertaindigits•android:singleLine,tocontrolifthefieldisforsingle-lineinputormultiple-lineinput(e.g.,doesmoveyoutothenextwidgetoraddanewline?) 除了这些,你可以使用专门配置字段输入方法,如android:仅数字输入numeric,android:为笼罩密码输入密码,还有Android:phoneNumber进入电话号码。如果你想创建自己的输入法计划(如邮政编码,社会安全号码),您需要创建自己的执行情况InputMethod接口,然后通过android设定字段来使用:inputMethod。例如,从theBasic/Field项目,这里是一个XML布局文件显示EditText:请注意android:singleLine是错误的,因此,用户将能够输入几行文字。对于这一项目,FieldDemo.java文件填充了一些散文输入栏:packagecom.commonsware.android.basic;importandroid.app.Activity;importandroid.os.Bundle;importandroid.widget.EditText;publicclassFieldDemoextendsActivity{@OverridepublicvoidonCreate(Bundleicicle){super.onCreate(icicle);setContentView(R.layout.main);EditTextfld=(EditText)findViewById(R.id.field);fld.setText("LicensedundertheApacheLicense,Version2.0"+"(the"License");youmaynotusethisfile"+"exceptincompliancewiththeLicense.Youmay"+"obtainacopyoftheLicenseat"+"http://www.apache.org/licenses/LICENSE-2.0"); }}结果,一旦建成并投入安装成模拟器,如图6-3所示。图6-3示例应用程序的FieldDemo注意:Android的模拟器只允许在每一个独特的Java包发射器中应发射用。由于本章中的所有演示共享com.commonsware.android.basic包,您将只能在你的模拟器发射的任何时候的看到这些演示之一。另一个字段的特色,提供自动完成,以帮助用户在整个无文本输入一个值。这是作为AutoCompleteTextView部件在Android中提供的并将在第8章讨论。另一种复选框经典的复选框有两种状态:选中的和未选中的。在这两种状态之间点击复选框切换来指示选择(例如,“添加快递到我的命令”)。在Android中,还有一个CheckBox控件,以满足这种需要。它作为一个TextView先驱,因此您可以像Android使用TextView性能:格式部件添加文字颜色。在Java中,你可以调用: •isChecked()todetermineifthecheckboxhasbeenchecked•setChecked()toforcethecheckboxintoacheckedoruncheckedstate•toggle()totogglethecheckboxasiftheusercheckedit此外,当复选框的状态发生改变时,你可以注册一个侦听器(这种情况下,一个OnCheckedChangeListener实例)来提醒。例如,从theBasic/CheckBox的项目,这里是一个简单的复选框的布局:相应的CheckBoxDemo.java检索和配置checkbox的行为:publicclassCheckBoxDemoextendsActivityimplementsCompoundButton.OnCheckedChangeListener{CheckBoxcb;@OverridepublicvoidonCreate(Bundleicicle){super.onCreate(icicle);setContentView(R.layout.main);cb=(CheckBox)findViewById(R.id.check);cb.setOnCheckedChangeListener(this);}publicvoidonCheckedChanged(CompoundButtonbuttonView,booleanisChecked){if(isChecked){cb.setText("Thischeckboxis:checked");}else{cb.setText("Thischeckboxis:unchecked"); }}}请注意为复选框的状态变化activity作为其自身监听器,因为它执行OnCheckedChangeListener分界面(通过cb.setOnCheckedChangeListener(this))。回调侦听器在onCheckedChanged(),它接收复选框的状态有什么新的变化和状态。在这种情况下,我们更新了文本的复选框来反映复选框中包含的实际内容。结果呢?点击复选框立即更新其内容,你可以看图6-4和6-5。图6-4CheckBoxDemo示例应用程序,未选中的复选框 图6-5同样的应用,选中的复选框打开收音机由于与其他单选按钮在其他工具包执行时,Android的单选按钮是两种状态,如复选框,但可分为这样,只有一组中的单选按钮可以随时选中。像复选框,RadioButton从CompoundButton中继承,从而继承了TextView。因此,所有的标准TextView的字体,样式,颜色等特性,可用于控制单选按钮的外观。同样,您可以在一个单选按钮上调用isChecked(),看看它是否被选中,切换()来选择它,等等,就像你可以用一个复选框。大多数时候,你会想要在RadioGroup里面放进一个RadioButton的小部件。该RadioGroup表明其状态的单选按钮设置联系在一起,这意味着只有一个按钮退出组可以在任何时间选择。如果您指派一个android:在您的XML布局中ID到你的RadioGroup,您可以访问您的Java代码和调用组:•check()tocheckaspecificradiobuttonviaitsID(e.g.,group.check(R.id.radio1))•clearCheck()toclearallradiobuttons,sononeinthegrouparechecked•getCheckedRadioButtonId()togettheIDofthecurrently-checkedradiobutton(or-1ifnonearechecked) 例如,theBasic/RadioButton的示例应用程序,这里是一个XML布局显示一个RadioGroup包装的RadioButton的部件集合:图6-6显示了使用Android生成的Java项目和此布局的结果 图6-6示例应用程序的RadoiButtonDemo请注意,单选按钮组最初设置为在一开始就完全畅通无阻。预先设定的一个单选按钮被选中,在RadioButton上使用setChecked()或从您的OnCreate()在activity中回调,在RadioGroup上选中()。所有部件,包括以前的那些示例,扩展视图,这样使所有部件一系列有用的性能,并超越那些已经介绍的方法。视图中最有可能被使用的某些属性,包括:•Controlsthefocussequence:•android:nextFocusDown•android:nextFocusLeft•android:nextFocusRight•android:nextFocusUp•android:visibility,whichcontrolswhetherthewidgetisinitiallyvisible•android:background,whichtypicallyprovidesanRGBcolorvalue(e.g.,#00FF00forgreen)toserveasthebackgroundforthewidget您可以切换是否通过setEnabled()启用了一个小装置,看看它是否是通过isEnabled()启用的。这是禁用一个复选框或单选按钮选择一些小部件的常用方式。你可以通过requestFocus()给出一个部件重点,看看它是否是通过isFocused()为重点。你可能会如前所述用禁用插件来使用,以确保一旦您禁用操作完成,正确的部件具有焦点。为了帮助操纵部件树和容器,组成一个activity的整体视图,你可以使用:•getParent()tofindtheparentwidgetorcontainer•findViewById()tofindachildwidgetwithacertainID•getRootView()togettherootofthetree(e.g.,whatyouprovidedtotheactivityviasetContentView())

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。
关闭