




已阅读5页,还剩6页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
外文资料原文BeginningAndroidMarkL.MurphyUsingXML-BasedLayoutsWhileitistechnicallypossibletocreateandattachwidgetstoouractivitypurelythroughJavacode,thewaywedidinChapter4,themorecommonapproachistouseanXML-basedlayoutfile.Dynamicinstantiationofwidgetsisreservedformorecomplicatedscenarios,wherethewidgetsarenotknownatcompile-time(eg.,populatingacolumnofradiobuttonsbasedondataretrievedofftheInternet).Withthatinmind,itstimetobreakouttheXMLandlearnhowtolayoutAndroidactivitiesthatway.WhatIsanXML-BasedLayout?Asthenamesuggests,anXML-basedlayoutisaspecificationofwidgetsrelationshipstoeachotherandtotheircontainers(moreonthisinChapter7)encodedinXMLformat.Specifically,AndroidconsidersXML-basedlayoutstoberesources,andassuchlayoutfilesarestoredintheres/layoutdirectoryinsideyourAndroidproject.EachXMLfilecontainsatreeofelementsspecifyingalayoutofwidgetsandtheircontainersthatmakeuponeviewhierarchy.TheattributesoftheXMLelementsareproperties,describinghowawidgetshouldlookorhowacontainershouldbehave.Forexample,ifaButtonelementhasanattributevalueofandroid:textStyle=bold,thatmeansthatthetextappearingonthefaceofthebuttonshouldberenderedinaboldfacefontstyle.AndroidsSDKshipswithatool(aapt)whichusesthelayouts.ThistoolshouldbeautomaticallyinvokedbyyourAndroidtoolchain(e.g.,Eclipse,Antsbuild.xml).OfparticularimportancetoyouasadeveloperisthataaptgeneratestheR.javasourcefilewithinyourproject,allowingyoutoaccesslayoutsandwidgetswithinthoselayoutsdirectlyfromyourJavacode.WhyUseXML-BasedLayouts?MosteverythingyoudousingXMLlayoutfilescanbeachievedthroughJavacode.Forexample,youcouldusesetTypeface()tohaveabuttonrenderitstextinbold,insteadofusingapropertyinanXMLlayout.SinceXMLlayoutsareyetanotherfileforyoutokeeptrackof,weneedgoodreasonsforusingsuchfiles.Perhapsthebiggestreasonistoassistinthecreationoftoolsforviewdefinition,suchasaGUIbuilderinanIDElikeEclipseoradedicatedAndroidGUIdesignerlikeDroidDraw1.SuchGUIbuilderscould,inprinciple,generateJavacodeinsteadofXML.Thechallengeisre-readingtheUIdefinitiontosupporteditsthatisfarsimplerifthedataisinastructuredformatlikeXMLthaninaprogramminglanguage.Moreover,keepinggeneratedXMLdefinitionsseparatedfromhand-writtenJavacodemakesitlesslikelythatsomebodyscustom-craftedsourcewillgetclobberedbyaccidentwhenthegeneratedbitsgetre-generated.XMLformsanicemiddlegroundbetweensomethingthatiseasyfortool-writerstouseandeasyforprogrammerstoworkwithbyhandasneeded.Also,XMLasaGUIdefinitionformatisbecomingmorecommonplace.MicrosoftsXAML2,AdobesFlex3,andMozillasXUL4alltakeasimilarapproachtothatofAndroid:putlayoutdetailsinanXMLfileandputprogrammingsmartsinsourcefiles(e.g.,JavaScriptforXUL).Manyless-well-knownGUIframeworks,suchasZK5,alsouseXMLforviewdefinition.While“followingtheherd”isnotnecessarilythebestpolicy,itdoeshavetheadvantageofhelpingtoeasethetransitionintoAndroidfromanyotherXML-centeredviewdescriptionlanguage.OK,SoWhatDoesItLookLike?HereistheButtonfromthepreviouschapterssampleapplication,convertedintoanXMLlayoutfile,foundintheLayouts/NowReduxsampleproject.ThiscodesamplealongwithallothersinthischaptercanbefoundintheSourceCodeareaof.TheclassnameofthewidgetButtonformsthenameoftheXMLelement.SinceButtonisanAndroid-suppliedwidget,wecanjustusethebareclassname.Ifyoucreateyourownwidgetsassubclassesofandroid.view.View,youwouldneedtoprovideafullpackagedeclarationaswell.TherootelementneedstodeclaretheAndroidXMLnamespace:xmlns:android=/apk/res/androidAllotherelementswillbechildrenoftherootandwillinheritthatnamespacedeclaration.BecausewewanttoreferencethisbuttonfromourJavacode,weneedtogiveitanidentifierviatheandroid:idattribute.Wewillcoverthisconceptingreaterdetaillaterinthischapter.TheremainingattributesarepropertiesofthisButtoninstance:android:textindicatestheinitialtexttobedisplayedonthebuttonface(inthiscase,anemptystring)android:layout_widthandandroid:layout_heighttellAndroidtohavethebuttonswidthandheightfillthe“parent”,inthiscasetheentirescreentheseattributeswillbecoveredingreaterdetailinChapter7.Sincethissinglewidgetistheonlycontentinouractivity,weonlyneedthissingleelement.ComplexUIswillrequireawholetreeofelements,representingthewidgetsandcontainersthatcontroltheirpositioning.AlltheremainingchaptersofthisbookwillusetheXMLlayoutformwheneverpractical,sotherearedozensofotherexamplesofmorecomplexlayoutsforyoutoperusefromChapter7onward.WhatswiththeSigns?ManywidgetsandcontainersonlyneedtoappearintheXMLlayoutfileanddonotneedtobereferencedinyourJavacode.Forexample,astaticlabel(TextView)frequentlyonlyneedstobeinthelayoutfiletoindicatewhereitshouldappear.ThesesortsofelementsintheXMLfiledonotneedtohavetheandroid:idattributetogivethemaname.AnythingyoudowanttouseinyourJavasource,though,needsanandroid:id.Theconventionistouse+id/.astheidvalue,wherethe.representsyourlocallyuniquenameforthewidgetinquestion.IntheXMLlayoutexampleintheprecedingsection,+id/buttonistheidentifierfortheButtonwidget.Androidprovidesafewspecialandroid:idvalues,oftheformandroid:id/.Wewillseesomeoftheseinvariouschaptersofthisbook,suchasChapters8and10.WeAttachThesetotheJavaHow?GiventhatyouhavepainstakinglysetupthewidgetsandcontainersinanXMLlayoutfilenamedmain.xmlstoredinres/layout,allyouneedisonestatementinyouractivitysonCreate()callbacktousethatlayout:setContentView(R.layout.main);ThisisthesamesetContentView()weusedearlier,passingitaninstanceofaViewsubclass(inthatcase,aButton).TheAndroid-builtview,constructedfromourlayout,isaccessedfromthatcode-generatedRclass.AllofthelayoutsareaccessibleunderR.layout,keyedbythebasenameofthelayoutfilemain.xmlresultsinR.layout.main.Toaccessouridentifiedwidgets,usefindViewById(),passinginthenumericidentifierofthewidgetinquestion.ThatnumericidentifierwasgeneratedbyAndroidintheRclassasR.id.something(wheresomethingisthespecificwidgetyouareseeking).ThosewidgetsaresimplysubclassesofView,justliketheButtoninstancewecreatedinChapter4.Marketisthemediumbetweendevelopersandusers,henceitsveryimportant.Somepredictedthattherewillbemoreandmoreapplicationmarketswhilesomedontthinkso.Incurrentmarkets,bothdoexist.Somespecifyonlyonemarketfortheirproducts,whileothersselltheirsoftwaresinvariousmarkets.SoftwaresfromNokia,MicrosoftandLinuxMobilearesoldineverymarket.Developersoftheseplatformscanreleasetheirownapplicationinwhatevermarkets,somarketshavetocompetewitheachotherforaliving.Thisisgoodforusers.However,thelackofuniversalmanagementmayleadtomessandchaos,softwaresthathavethesamefunctionalityexistindifferentmarkets,whichconfusesusersalot.Correspondingly,solemarketsclaimthatmostapplicationsshouldbesoldinthem.Thiskindofmonopolizationleadstonocompetitor.AppStoreandAndroidMarketaredeputyofsolemarkets.Normally,iPhoneapplicationscanonlybefoundinAppStore,andApplewillcheckeveryoneofthembyitself.GoodnewsisthateveryapplicationinAppStoreisofficiallytested,itssafe;Badnewsisthatalotofprettygoodsoftwaresarerejectedforvariousreasons.Andabigunofficialmechanismisbuiltbyhackers,thatisjailbreakandSIMunlock.JailbreakisaprocessthatallowsiPad,iPhoneandiPodTouchuserstogainrootaccessandunlocktheoperatingsystemthusremovinganylimitationsimposeduponthembyApple.Oncejailbroken,iPhoneusersareabletodownloadmanyextensionsandthemespreviouslyunavailablethroughtheAppStoreviainstallerssuchasCydia.AjailbrokeniPad,iPhoneoriPodTouchisstillabletousetheAppStoreandiTunes9.AndaSIMlockisacapabilitybuiltintoGSMphonesbymobilephonemanufacturers.Networkprovidersusethiscapabilitytorestricttheuseofthesephonestospecificcountriesandnetworkproviders.Generally,phonescanbelockedtoacceptonlySIMcardsbasedontheInternationalMobileSubscriberIdentity.SIMunlockmakeitpossibletouseamobilephonewithoutconsideringcountriesandnetworksspecifiedbymobilephonemanufacturers.HoweverinAndroid,Googledoesnttesteveryapplicationatall,soalthoughtheresanofficialmarketforAndroidapplications,youcanstillreleaseyourproductanywhereyouwant.Consideringsecurityproblems,Googlebannedtheuseofsomecomponents.LikejailbreakandSIMunlockiniPhone,rootinAndroidgivesusers100%controloftheirdevices,alongwithsomesecurityrisks.RootisaprocessthatallowsusersofcellphonesrunningtheAndroidoperatingsystemtoattainprivilegedcontrol(knownasrootaccess)withinAndroidsLinuxsubsystem,similartojailbreakingonAppledevicesrunningtheiOSoperatingsystem,overcominglimitationsthatthecarriersandmanufacturersputonsuchphones.RootingmakesitpossibletousecustomversionsoftheAndroidsystemsuchasCyanogenMod,supportingfeaturesunavailableinstockROMs.ItalsoallowsfornewerversionsofAndroidnotsuppliedbytheoriginaldevicemanufacturer.IncontrasttoiOSjailbreaking,rootingisnotneededtorunapplicationsnotdistributedbytheofficialAndroidMarket.Itisneededhowever,whentryingtoaccesspaidAndroidapplicationsfromcountrieswhicharenotpartofthepaidapplicationsmarket.译文Android起航MarkL.Murphy使用XML进行布局虽然纯粹通过Java代码在activity上创建和添加部件,在技术上是可行的,我们在第4章中做的一样,更常见的方法是使用一种基于XML的布局文件。动态的小部件实例保留更多,情况复杂,小工具在编译时不为人所知(例如,在数据检索了互联网基础上将单选按钮填充柱。考虑到这一点,现在是时候打破XML来学习如何用此种方式来布置Androidactivities。什么是基于XML的布局?正如其名称所示,一个基于XML的布局是一个关系到每个规格的小部件,和他们的容器(更多关于此内容的在第7章)编码的XML格式。具体来说,Android认为基于XML的布局是资源,因此布局文件存储在res/在你的Android项目布局目录中。每个XML文件包含一个指定的部件和容器布局元素树,一种意见认为构成层次。对XML元素的属性,描述一个部件应如何看或者一个容器应如何运转。例如,如果一个按钮元素。有一个Android的属性值:文字样式=“bold”,这意味着该文本出现在按钮的表面应该是呈现一个粗体字体样式.Android的SDK中附带一个使用的布局的工具(aapt)。这个工具应自动调用你的Android工具链(例如,Eclipse中,Antsbuild.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示例项目,在这一章中可以找到源代码的领域。部件,按钮的类名称形成XML元素的名称。因为按钮是Android提供的部件,我们可以只使用裸类的名称。如果您创建自己的部件作为android.view.View子小部件,您也将需要提供一个完整的包声明(如monsware.android.MyWidget)。根元素需要Android的XML命名空间声明:xmlns:android=/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
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2019-2025年期货从业资格之期货法律法规能力提升试卷A卷附答案
- 辽宁抚顺历年中考作文题与审题指导(2010-2023)
- 新产品市场调研与市场准入分析合同
- 环保工程采购咨询及招标代理服务全面合作协议
- 生态农业园区场地租赁合同终止与农产品合作协议
- 私家车挂靠出租车公司合作经营协议书
- 安徽省皖江名校2024-2025学年高一下学期5月月考英语史试题(B)(含答案)
- 样品检验报告
- 厂房拆除施工全过程安全控制与管理协议
- 仓储物流中心厂房租赁合同规范
- 《“妙乎”回春》为例,从角色、故事、结构、动作、语言、剧场元
- 小学综合实践活动四年级下册全册教学设计上海科技教育出版社
- 人人都是产品经理 苏杰
- 年产5万吨电石炉窑节能改造项目环境影响后评价报告
- 五年级下学期数学第六单元第5课时《单元综合复习》课件(共15张PPT)人教版
- 贪污贿赂犯罪PPT(培训)(PPT168页)课件
- (整理)体适能课程教学计划.
- 洛阳市中小学教师师德师风考核内容和评分细则
- 休克的急救护理课件
- 烟草专卖局(公司)系统绩效考核管理办法(讨论稿)
- 项目核算管理办法(修改)
评论
0/150
提交评论