android应用之火车行开发科技文献摘译_第1页
android应用之火车行开发科技文献摘译_第2页
android应用之火车行开发科技文献摘译_第3页
android应用之火车行开发科技文献摘译_第4页
android应用之火车行开发科技文献摘译_第5页
已阅读5页,还剩10页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Beginning Using XML-Based While it is sible to create and attach widgets to our activity purely Java code, the way we did in Chapter 4, the more common approach is to use an XML-layoutfile.DynamicinstantiationBeginning Using XML-Based While it is sible to create and attach widgets to our activity pu

2、rely Java code, the way we did in Chapter 4, the more common approach is to use an XML-layoutfile.Dynamicinstantiationofwidgetsformorecomplicatedscenarios,thewidgetsarenotknownatcompile-time(eg.,populatingacolumnofradiobuttonsbaseddataretrieved off ttind, its time to break out the XML and learn how

3、to lay out WhatIsanXML-BasedAsthenamesuggests,anXML-basedlayoutisaspecificationofwidgetsrelationshipsto each otherand to their containers (more on this in Chapter 7)encoded in XML Specifically,AndroidconsidersXML-basedlayoutstobe,andchlayoutfilesheres/layoutdirectoryinsideyourAndroidEach XML file co

4、ntains a tree of elements specifying a layout of widgets and tmakeuponeviewhierarchy.TheattributesoftheXMLelementsaredescribinghowawidgetshouldlookorhowacontainershouldForle, if a Button s an attribute value of android:textStyle = tt the text appearing on the face of the button should be rendered in

5、 a boldface Androids SDK ships with a tool (aapt) which uses the layouts. This tool should automaticallyinvokedbyyourAndroidtoolchain(e.g.,Eclipse,AntsOfparticularimportancetoyouasadevelopertaaptgeneratestheR.javasourcewithin your project, allowing you to fromyourJava s layouts and widgets hose layo

6、uts Why Use XML-Based Most everything you do using XMLlayout files can be achieved through Java code. le,youcouldusesetTypeface()tohave abuttonrender itstextin bold,insteadof aproperty in an XMLlayout. Since XMLlayouts are yet another file for you to keep track weneedgoodreasonsforusing suchPerhaps

7、the biggest reason is to he creation of tools for view definition, such a GUI builder in an IDE like Eclipse or a dedicated Android GUI designer like Suchweneedgoodreasonsforusing suchPerhaps the biggest reason is to he creation of tools for view definition, such a GUI builder in an IDE like Eclipse

8、 or a dedicated Android GUI designer like SuchGUIbuilderscould,inprinciple,generateJavacodeinsteadofXML.ThechallengeisreadingtheUIdefinitiontosupporttisfarsimplerifthedataisinastructuredlike n in a programming language. Moreover, ng generated XML separated from hand-written Java code makes it less t

9、 somebodys custom-source will get clobbered by accident when erated bits get re-generated. XML forms t is easy for tool-writers to use and easy nice middle ground n programmerstoworkwithbyhandasAlso, XML as a GUI definition format ing more XAML2, Adobes Flex3, and Mozillas XUL4 all take a similar ap

10、proach t of put layout details in an XML file and put programming smarts in source files (e.g., for XUL). Many less-well-known GUI frameworks, such as ZK5, also use XML for definition. While “following the herd” is not sarily the best policy, it does have advantage of to ease the o Android from any

11、other XML-centered description language. layout file, he Layouts owRedux le project. This sle along ll .his chapter can be he Source Code area ?xml=1.0encoding=utf-Buttonxmlns:android= HYPERLINK http:/s/ http:/s The class name of the widgetButtonforms the name of the XML element. Button is an d widg

12、et, we can just use the bare ame. If you create own widgets bclasses of android.view.View, you would need to provide a full declarationas TheementneedstodeclaretheAndroidXML HYPERLINK http:/s/ AllotherelementswillbechildrenoftherootandwilltnamespaceBecause we want to reference this button from our J

13、ava code, we need to give it identifier via the android:id attribute. We will cover this concept in greater detail later Theremainingattributesare propertiesofthisButton android:textindicates the initial text to be displayed on the button face empty his case,Because we want to reference this button

14、from our Java code, we need to give it identifier via the android:id attribute. We will cover this concept in greater detail later Theremainingattributesare propertiesofthisButton android:textindicates the initial text to be displayed on the button face empty his case, and height fill the “parent”,g

15、reaterdetail inChapterndlAndroidtohavethebuttonshis case the entire screenthese attributes will be covered ComplexUIswillrequireawholetreeofelements,representingthewidgetsandtcontrolitioning.AlltheremainingchaptersofthisbookwillusetheXMLlayoutractical, so there are dozens of other les of more comple

16、x layouts for you peruse fromChapter 7 WhatswiththeManywidgets andcontainers onlyneed to he XMLlayout file anddo not tobereferencedinyourJavacode.Forle,aiclabel(TextView)frequentlyonlyto he layout file to indicate where it should appear. These sorts of he filedo notneed to havethe android:idattribut

17、e to givethem aAnythingyoudowanttouseinyourJavasource,though,needsanThe convention is to use +id/. as the id value, where the . represents locallyunique name for the widget in he XML layout he section,+id/buttonistheidentifierfortheButtonAndroidprovidesafewlandroid:idvalues,oftheformWewillsomeofthes

18、einvariouschaptersofthisbook,suchasChapters8andWeAttachThesetotheJavatyouhavepainstakinglysetupthewidgetsandcontainersinanXMLlayoutnamedmain.xmlstoredinres/layout,allyouneedisoneementinyouractivityscallbackto tlayout: This is the same setContentView() we used r, passing it an instance of a subclass

19、t case, a Button). The Android-built view, constructed from our layout, sed t code-generated R class. All of the layouts are sible under keyedby thebase nameofthelayoutfilemain.xmlresults in Tosouridentifiedwidgets,usefindViewById(),henumericidentifierthe widget in t numeric identifier was generated

20、 by he R class R.id.somethingTosouridentifiedwidgets,usefindViewById(),henumericidentifierthe widget in t numeric identifier was generated by he R class R.id.something (where something is the specific widget you are seeking). Those widgets simplysubclassesofView,justliketheButtoninstancewecreatedinC

21、hapterThe Rest of the heoriginalNowdemo, the buttonsfacewould showthe time,whichwouldreflectwhenthebuttonwaslastpushed(orwhentheactivityif the button had not yet been pushed). Most tlogicstillworks, his revised wecanreferencetheonefromthe XMLimportandroid.app.Activity; import android.os.Bundle; impo

22、rt android.view.View;importandroid.widget.Button;importpublicowReduxivityimplementsView.OnClickListenerButtonpublic void onCreate(Bundle icicle) super.onCreate(icicle); publicvoidonClick(Viewview)privatevoid btn.setText(new difference t n setting the content view to be a view we created Javacode,wes

23、etittoreferencetheXMLlayout(setContentView(R.layout.main).TheR.java sourcefilewillbeupdatedwhenwerebuildthisprojecttoincludeareferencetoourlayout(storedas main.xmlin ourprojectsres/layout TheotherdifferencetweneedtogetourhandsonourButtoninstance,forwhichuse the findViewById() call. Since we identifi

24、ed our button as +id/button, we can the buttons identifier as R.id.button. Now, with the Button instance in hand, we can set callbackandsetthelabelasEmploying Basic EveryGUIssomebasicwidgets:fields,labels,buttons,etc.Androidstoolkitnodifferentinscope,andthebasiccallbackandsetthelabelasEmploying Basi

25、c EveryGUIssomebasicwidgets:fields,labels,buttons,etc.Androidstoolkitnodifferentinscope,andthebasicwidgetswillprovideaworkinAndroidroductionastohowThesimplest widget is the label, referred to inAndroid as a TextView. ost toolkits,labelsarebitsoftextnoteditabledirectlybyusers.Typically,theyareusedtoi

26、dentify adjacent widgets (e.g., a “Name:” label before a field where one fills in a name).InJava,youcancreatealabelbycreatingaTextViewinstance.Morecommonly,youwillabelsinXMLlayoutfilesbyaddingaTextViewelementtothelayout,nandroid:text property to set the value of the label itself. If you need to swap

27、 labels based certain criteria, such ernationalization, you may wish to use a resource XML instead, as will be described in Chapter 9. TextView has numerous roperties relevanceforlabels,ForheBasic/Labelproject,youwillfindthefollowing?xml=1.0encoding=utf- HYPERLINK http:/s/ android:text=Youwereexpect

28、ingsomethingprofound?Button,WhosGottheWevealreadyseentheuseoftheButtonwidgetinChapters4and5.Asitturnsout,Button is a subclass of TextView, so everything discussed in the preceding section in terms of formatting the face of the button still holds.Android has two widgets to help you embed images in yo

29、ur activities: ImageView ImageButton.As theggest,theyare image-oguestoTextView and respectively. Each widget takes an android:src attribute (in an XML layout) to specify picture to use. These usually reference a drawable resource, described in greater chapteron.YousosettheimagecontentbasedonaUrifrom

30、acontentvia ImageButton, a subclass of ImageView, mixes responding to clicks and whatnot.he standard Button behaviors, le,ekatthemain.xmllayoutfromtheBasic/ImageViewvia ImageButton, a subclass of ImageView, mixes responding to clicks and whatnot.he standard Button behaviors, le,ekatthemain.xmllayout

31、fromtheBasic/ImageViewle?xml=1.0encoding=utf- HYPERLINK http:/s/ android:src=drawable/moleculeFieldsofGreen.OrOtherAlong with buttons and labels, fields are the third “anchor” of most GUI toolkits. In Android, they are implemented via the EditText widget, which is a subclass of the TextView used for

32、 labels.AlongwiththestandardTextViewproperties(e.g.,android:textStyle),EditTex st will be useful for you in constructing fields, including: Beyond those, you configure fields to use lized input methods, such as android:numeric for numeric-input, android:password for shrouded password input, and andr

33、oid:phoneNumber for in phone numbers. If you want to create your own input method scheme tal l Security numbers), you need to create your own ion of the erface, then configure the field to use it via android: inputMethod. For Basic/Fieldproject,hereisanXMLlayoutfileshowingan le, from ?xml=1.0encodin

34、g=utf- HYPERLINK http:/s/ android:singleLine=false/apk/res/androidtandroid:singleLineisfalse,souserswillbeabletoenterinseverallinesofForthistandroid:singleLineisfalse,souserswillbeabletoenterinseverallinesofForthisproject,theFieldDemo.javafilepopulatestheinputfieldwithsomeimport android.app.Activity

35、; import android.os.Bundle; publicclassFieldDemoivity publicvoidonCreate(Bundleicicle)super.onCreate(icicle); fld.setText(Licensed under the Apache License, 2.0 + (the License); may not use this file + except in compliance with the License. You may + obtain a ofthe Licenseat + Note Androids emulator

36、 only allows one application in the launcher per unique package. Since all the demos in this chapter share package,youwillonlyseeoneofthesedemosinyouremulatorslauncheratanyone Another flavor of field is t pletion, to help pply a without he whole t is provided inAndroid as widgetandisdiscussedinChapt

37、erAndroid1使用XML 进行Java activity 在实 基于XML 的布局XML 的容器7 Android1使用XML 进行Java activity 在实 基于XML 的布局XML 的容器7 章)XML 格式。具体来说,Android XML resAndroid XML Android的SDK 中附带一个使用的布局的工具(aapt。这个工具应自动调用你的 build.xml 。为什么基于XML 的布局 EclipseDroidDraw1GUIGUI XML Java 此外,XML GUI XAML,Adobe Flex,Mozilla XUL Android XML XML

38、Java 此外,XML GUI XAML,Adobe Flex,Mozilla XUL Android XML 文件和把编程智慧资料放在源文件(例如,XUL 中的 JavaScript。许多不太知名的图形用户界面框架,如 ZK,还使用视图定义的 XML。而“随大流”并不一定是最好的政策,但他们有优势帮助从任何其他 XML 为中心的观点描述语言轻松进入 Android。 ?xml=1.0encoding=utf-Buttonxmlns:android= HYPERLINK http:/s/ http:/s XML Android 们可以只使用 类的名称。如果您创建自己 monsware.andr

39、oid.Myidget也将需要提供一个完整的(id 要 android:layout_width Android:layout_heightandroid activity 用 符用途许和容器只需要出现在 XML 在 Java android:idJavaandroid:id XML布局的例子中,+id 。符用途许和容器只需要出现在 XML 在 Java android:idJavaandroid:id XML布局的例子中,+id 。androidandroid:ID值,形式android:id/. activity OnCreate()setContentie(, 成的 R in R.lay

40、out键控布局文件的名称要findiewByI(字标识符生成的R 类由android 在R.id.somethin(Button Now 演示中,按钮的表面便会显示当前的时间,这将反映当 的实例, 可以从 XMLimport android.app.Activity; import android.os.Bundle; import android.view.View; import publicowRedux publicvoidonCreate(Bundle super.onCreate(icicle); privatevoid第一个区别是,在 Java 的 (setContentie(R

41、.layout.mainpublicvoidonCreate(Bundle super.onCreate(icicle); privatevoid第一个区别是,在 Java 的 (setContentie(R.layout.main 在 main.xml in our projects 这个项目,包括对directory 布局参考文件然2使用基本GUI ,按钮等,Android在 在范围内没有不同,其基本activities将提供一个良好的介绍,关于这些是Android TextViewGUIJavaTextViewlTextView XML Android,XML9 ?xml=1.0encoding=utf- HYPERLINK http:/s/ android:text=Youwereexpectin

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论