1、附录 I 英文原文Beginning Android1. .U sin g X M L -B a sed L a y ou tsW hile i t i s technically possible to create and a ttach w idg ets to our activity purely throug h J ava code, the w ay w e did in C hapter 4 , the more com mon approach i s to use an X M L -based la y out fi le . Dy na mic instantiati
2、on of w idg ets i s reserved for more complicated scenarios, w here the w idg ets a re not know n a t com pile-time ( e g ., populating a colum n of radio buttons based on data retrieved off the Internet).W i th that in m ind, i ts tim e to break out the X M L and learn how to la y out A ndroid acti
3、vities that w a y.1.1 1W h a t Is a n X M L -B a sed L a y ou t?A s the name sug g ests, an X M L -based la y out is a specification of w idg ets re la tionships to each other and to their containers ( m ore on this in C hapter 7 ) encoded in X M L format. S pecifically, A ndroid considers X M L -ba
4、sed la y outs to be resources, and as such lay out fi les are stored in the res /la y out directory inside y our A ndroid project.Each X M L fi le contains a tree of e lem ents specify ing a lay out of w idg ets and their containers that make up one v iew hierarchy. The a ttributes of the X M L e le
5、m ents a re properties, describing how a w idg et should look or how a container should behave. For ex ample, if a B utton element has an a ttribute value of android: tex tS ty le = bold, that means that the text appearing on the face of the button should be rendered in a boldface font sty le.A ndro
6、ids S DK ships w ith a tool ( aapt) w hich uses the lay outs. This tool should be automatically invoked by y our A ndroid tool chain ( e .g ., Eclipse, A nts build.x ml). Of particular im portance to y ou as a developer i s that aapt g enerates the R .java source fi le w i thin y our project, a l lo
7、w ing y ou to access lay outs and w idg ets w i thin those l a y outs directly from y our J ava code.1.2 2W h y U se X M L -B a sed L a y ou ts?M ost every thing y ou do using X M L la y out fi les can be achieved throug h J ava code. For ex ample, y ou could use setTy peface() to have a button rend
8、er i ts tex t in bold, instead of using a property in an X M L lay out. S ince X M L la y outs are y et another fi le for y ou to keep track of, w e need g ood reasons for using such files.Perhaps the big g est reason i s to assist in the creation of tools for view definition, such as a GU I builder
9、 in an IDE like Eclipse or a dedicated A ndroid GU I desig ner like DroidDraw 1 . S uch GU I builders could, in principle, g enerate J ava code instead of X M L. The challeng e i s re-reading the U I definition to support edits that i s far s im pler if the data is in a structured format l ike X M L
10、 than in a prog ram ming lang uag e . M oreover, keeping g enerated X M L definitions separated from hand-w ri tten J ava code makes i t less l ikely that som ebody s custom -c ra fted source w i l l g et clobbered by accident w hen the g enerated bits g et re-g enerated. X M L form s a nice m iddle
11、 g round betw een som ething that i s easy for tool-w riters to use and easy for prog ramm ers to w ork w i th by hand as needed.A l so, X M L as a GU I definition form a t i s becom ing more com monplace. M icrosofts X A M L 2 , A dobe s Flex 3 , and M ozilla s X U L 4 a l l take a sim i la r appro
12、ach to that of A ndroid: put la y out details in an X M L fi le and put prog ramm ing smarts in source files ( e .g ., J ava S cript for X U L).M any less-w el l -know n GU I framew orks, such as ZK5 , a l so use X M L for view definition. W hile “fol low ing the herd”is not necessarily the best pol
13、icy, i t does have the advantag e of helping to ease the transition into A ndroid from any other X M L -centered view description lang uag e .la y out fi le , found in the La y outs /Now R edux sam ple project. This code sample a long w i th a ll others in this chapter can be found in the S ource C
14、ode a rea of http:/ .The c la ss name of the w idget B utton forms the name of the X M L element. S ince B utton is an A ndroid-supplied w idg et, w e can just use the bare class name. If y ou create y our ow n w idg ets as subclasses of android.view.View, y ou w ould need to provide a full packag e
15、 declaration as w ell.The root e lement needs to declare the A ndroid X M L nam espace: x mlns: android=http:/ schem /a pk /re s /a ndroidA l l other elements w i l l be children of the root and w i l l inherit that nam espace declaration.B ecause w e w ant to reference this button from our J ava co
16、de, w e need to g ive i t an identifier via the android: id a ttribute. W e w i l l cover this concept in g reater detail la ter in this chapter.The remaining a ttributes a re properties of this B utton instance: android: text indicates the initial tex t to be display ed on the button face ( in this
17、 case, an empty string ) android: lay out_ w idth and android: la y out_ heig ht te l l A ndroid to have the buttons w idth and heig ht fi l l the “pa rent”, in this case the entire screen these a ttributes w i l l be covered in g reater detail in C hapter 7 .S ince this sing le w idg et i s the onl
18、y content in our activity, w e only need this sing le e lement. C omplex U Is w i l l require a w hole tree of elements, representing the w idg ets and containers that control their positioning . A ll the remaining chapters of this book w i l l use the X M L lay out form w henever practical, so ther
19、e are dozens of other examples of more complex la y outs for y ou to peruse from C hapter 7 onw ard.1.3 3 W h a t s w ith th e S ign s?M any w idg ets and containers only need to appear in the X M L la y out fi le and do not need to be eferenced in y our J ava code. For example, a s ta tic label ( T
20、ex tView ) frequently only needs to be in the la y out fi le to indicate w here it should appear. These sorts of elem ents in the X M L file do not need to have the android: id attribute to g ive them a nam e.A ny thing y ou do w ant to use in y our J ava source, thoug h, needs an android: id.The co
21、nvention is to use +id/. as the id value, w here the . represents y our locally unique name for the w idg et in question. In the X M L lay out ex ample in the preceding section, +id/bu tton i s the identifier for the B utton w idg et.A ndroid provides a few special android: id values, of the form an
22、droid: id/. W e w i l l see some of these in various chapters of this book, such as C hapters 8 and 10 .W e A tta ch These to the J ava How ?Given that y ou have painstaking l y set up the w idg ets and containers in an X M L la y out filenamed main.x m l stored in res /la y out, a l l y ou need is
23、one sta tem ent in y our activity s onC reate() callback to use that lay out:setC ontentView ( R .la y out. main);This i s the same setC ontentView ( ) w e used earlier, passing i t an instance of a View subclass ( in that case, a B utton). The A ndroid-built view, constructed from our l ay out, i s
24、 accessed from that code-g enerated R c lass. A l l of the lay outs a re accessible under R .la y out, key ed by the base name of the lay out file m a in.x ml results in R .la y out. main.To access our identified w idg ets, use find View B y Id(), pa ssing in the numeric identifier of the w idg et i
25、n question. That numeric identifier w as g enerated by A ndroid in the R c lass as R .id.som ething ( w here som ething i s the specific w idg et y ou are seeking ) . Those w idg ets a re simply subclasses of View, just l ike the B utton instance w e created in C hapter 4 .The R est of the S tory In
26、 the orig inal Now demo, the buttons face w ould show the current time, w hich w ould reflect w hen the button w as la st pushed ( or w hen the activity w as first show n, if the button had not y et been pushed). M ost of that log ic still w orks, even in this revised dem o ( Now R edux ) . How ever
27、, rather than instantiating the B utton in our activity s onC reate() callback, w e can reference the one from the X M L l ay out:packag e monsw a re.android.lay outs; import android.app.A ctivity ;import android.os.B undle; import android.view.View ;import android.w idg et.B utton; import ja va.uti
28、l.Date;public class Now R edux ex tends A ctivity im plements View.OnC lick L istener B utton btn; Overridepublic void onC reate(B undle ic ic le) super.onC reate( icicle); setC ontentView ( R .lay out. main);btn=( B utton) find View B y Id( R .id.button); btn.setOnC l ick L i stener( this); update
29、Time();public void onC lick(View view ) update Tim e();private void update Time() btn.setTex t( new Date().toS tring ( ) ) ; The fi rst difference i s that rather than setting the content view to be a view w e created in J ava code, w e set i t to reference the X M L la y out ( setC ontentView ( R .
30、lay out.main). The R .ja va source file w i l l be updated w hen w e rebuild this project to include a reference to our lay out fil e ( stored as main.x ml in our projects res /la y out directory ) .The other difference i s that w e need to g et our hands on our B utton instance, for w hich w e use
31、the findView B y Id() call. S ince w e identified our button as +id/bu tton, w e can reference the buttons identifier as R .id.button. Now, w i th the B utton instance in hand, w e can set the callback and set the label as needed.2. .Em p loy in g B a sic W id g etsEvery GU I toolkit has some basic
32、w idg ets: fields, labels, buttons, etc. A ndroids toolkit i s no different in scope, and the basic w idg ets w i l l provide a g ood introduction as to how w idg ets w ork in A ndroid activities.The s im plest w idg et i s the label, referred to in A ndroid as a Tex tView. Like in m ost GU I toolki
33、ts, labels a re bits of tex t not editable directly by users. Ty pically, they a re used to identify adjacent w idg ets ( e .g ., a “Na m e: ”l abel before a fie ld w here one fi l l s in a name).In J ava, y ou can create a label by creating a Tex tView instance. M ore comm only, thoug h, y ou w i l
34、l create labels in X M L la y out fi les by adding a Tex tView element to the lay out, w i th an android: text property to set the value of the label i tself. If y ou need to sw ap labels based on certain criteria, such as internationalization, y ou ma y w i sh to use a resource reference in the X M
35、 L instead, as w il l be described in C hapter 9 . Tex tView has num erous other properties of relevance for labels, For ex am ple, in the B asic /L a bel project, y ou w il l find the follow ing la y out fi le : 2 .1B u t ton , W h os G ot th e B u t ton ?We v e a l ready seen the use of the B utto
36、n w idg et in C hapters 4 and 5 . A s i t turns out, B utton i s a subclass of TextView, so every thing discussed in the preceding section in term s of form a tting the face of the button sti l l holds.A ndroid has tw o w idg ets to help y ou em bed imag es in y our activities: Im ag e View and Im a
37、g e B utton. A s the nam es sug g est, they a re im ag e-based analog ues to Tex tView and B utton, respectively. Each w idg et takes an android: src a ttribute ( in an X M L la y out) to specify w hat picture to use. These usually reference a draw able resource, described in g reater detail in the
38、chapter on resources. You can a lso set the imag e content based on a U ri from a content provider via setImag e U R I().Imag e B utton, a subclass of Im ag e View, m ix es in the standard B utton behaviors, for responding to c licks and w hatnot. For ex ample, take a peek a t the m a in.x ml la y o
39、ut from the B asic /Im ag e View sam ple project: 2 .2 Fields of Green. Or Other C olors.A long w ith buttons and labels, fie lds a re the third “a nchor”of most GU I toolkits. In A ndroid, they are im plemented via the EditTex t w idg et, w hich i s a subclass of the Tex tView used for labels. A lo
40、ng w ith the standard Tex tView properties ( e.g ., android: tex tS ty le), EditTex t has many others that w i l l be useful for y ou in constructing fie lds, including : B ey ond those, y ou can config ure fie lds to use specialized input methods, such as android: numeric for numeric-only input, an
41、droid: passw ord for shrouded passw ord input, and android: phone Number for entering in phone num bers. If y ou w ant to create y our ow n input method scheme ( e .g ., postal codes, S ocial S ecurity num bers), y ou need to create y our ow n implem entation of the InputM ethod interface, then conf
42、ig ure the fie ld to use i t via android: inputM ethod. For ex am ple, from the B asic /Fie ld project,here i s an X M L la y out fi le show ing an EditTex t:Note that android: s ing le Line i s fa l se, so users w i l l be able to enter in several l ines of tex t. For this project, the FieldDem o.j
43、ava file populates the input fie ld w ith som e prose:packag e m onsw a re.android.basic; import android.app.A ctivity ;import android.os.B undle; import android.w idg et.EditTex t;public c lass Field Demo extends A ctivity Overridepublic void onC reate(B undle ic ic le) super.onC reate( icicle); se
44、tC ontentView ( R .la y out. main);EditTex t fld=(EditTex t) find View B y Id( R .id.field);fld.setTex t(Licensed under the A pache License, Version2 .0 + ( theL icense ) ; y ou m ay not use this fi le + ex cept in com pliance w i th the L icense. You m a y + obtain acopy ofthe L icense a t +http:/ w w w.apache.org /l icenses /L IC ENS E-2 .0 ) ;Note A ndroids em ulator only a l lo
版权声明:以上文章中所选用的图片及文字来源于网络以及用户投稿,由于未联系到知识产权人或未发现有关知识产权的登记,如有知识产权人并不愿意我们使用,如有侵权请立即联系:2622162128@qq.com ,我们立即下架或删除。
Copyright© 2022-2024 www.wodocx.com ,All Rights Reserved |陕ICP备19002583号-1
陕公网安备 61072602000132号 违法和不良信息举报:0916-4228922