Foundation Flash CS5 For Designers- P14

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:50

0
62
lượt xem
19
download

Foundation Flash CS5 For Designers- P14

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Foundation Flash CS5 For Designers- P14: Flash is one of the most engaging, innovative, and versatile technologies available-allowing the creation of anything from animated banners and simple cartoons to Rich Internet Applications, interactive videos, and dynamic user interfaces for web sites, kiosks, devices, or DVDs. The possibilities are endless, and now it just got better

Chủ đề:
Lưu

Nội dung Text: Foundation Flash CS5 For Designers- P14

  1. BUILDING INTERFACES WITH THE UI COMPONENTS Here’s an exercise designed to show you how the ProgressBar component works: 1. Open the ProgressBar.fla file in this chapter’s Exercise folder. Note that a ProgressBar instance exists in frame 1 with the instance name pb, as well as a text field with the instance name output. In frame 5, you’ll find a fairly heavy image of red leaves on a tree branch, snapped by one of the authors. In the scripts layer, there’s a MovieClip.stop() method in frames 1 and 5. 2. Click into frame 1 of the scripts layer. Note the existing stop() method. Type the following ActionScript after that method (new code in bold): stop(); root.loaderInfo.addEventListener(Event.COMPLETE, completeHandler); function completeHandler(evt:Event):void { play(); }; pb.source = root.loaderInfo; Here, first, the playhead stops at this frame. Next, an Event.COMPLETE handler is assigned to the LoaderInfo instance associated with the root property of the main timeline. Say again? Yeah, this one is a bit different from what you’ve seen. In the same way that the stop() method is invoked here on the main timeline—appearing, as it does, without an object reference prefix—the root property is also being invoked implicitly on the main timeline. (root is a property of the DisplayObject class, which means MovieClip and other classes have it by inheritance.) The root property refers to the topmost display object in a given display list. In this context, it essentially refers to the display list of the main timeline (everything that’s visible—or will be visible—on the main timeline, including that onion photo on frame 5). The main timeline, being a movie clip, features a loaderInfo property, which points to an instance of the LoaderInfo class that (as its name suggests) manages loading information for the object at hand. In this case, when the movie itself has completed loading, the Event.COMPLETE event is dispatched, and the completeHandler() function invokes MovieClip.play() on the main timeline, causing the playhead to resume play until it encounters the second stop() method on frame 5. It’s frame 5 that reveals the image. Notice that, so far, none of this yet touches the ProgressBar component. That happens only at this point. Immediately after the event handler, the ProgressBar.source property, by way of the pb instance, is associated with the root.loaderInfo reference. As if by magic, that’s all it takes to set the thermometer- style movement in motion. 3. Test the movie. When the SWF launches, select View ➤ Simulate Download from the SWF’s menu bar to see the ProgressBar component in action. Selecting View ➤ Download Settings lets you select the speed of the simulated Internet connection. 4. Close the SWF. 629 www.zshareall.com
  2. CHAPTER 11 5. Let’s also display a text message indicating a percent loaded. In the Actions panel, add a few more lines below the existing code: pb.addEventListener(ProgressEvent.PROGRESS, progressHandler); function progressHandler (evt:ProgressEvent):void { output.text = Math.floor(pb.percentComplete).toString() + "%"; }; The ProgressBar component features a percentComplete property, which we’re using here. The addEventListener() method is invoked against the pb instance, listening for a ProgressEvent.PROGRESS event. The function it performs sets the output text field’s text property to a rounded-down string version of the progress percentage, with the percent sign tacked onto the end for good measure. RadioButton component This book was purchased by flashfast1@gmail.com Radio buttons are gregarious. They belong in groups and courteously defer to each other as each takes the spotlight. What are we talking about? We’re talking about a component identical in functionality to radio buttons in HTML. Groups of RadioButton components are used to let the user make a single selection from a multiple-choice set, as shown in Figure 11-22. Figure 11-22. The RadioButton component lets the user make a single selection from a multiple-choice set. 630 www.zshareall.com
  3. BUILDING INTERFACES WITH THE UI COMPONENTS Double-clicking a RadioButton instance provides access to its skins, which you can edit as described in the “Button component” section. Styling works the same way. Using one or more instances of the RadioButton component in your movie will add 16KB to the SWF if no other components share the load. To see RadioButton components in action, open the RadioButton.fla file in this chapter’s Exercise file. Because radio buttons work in groups, the Component Parameters tab of the Properties panel has a “collective consciousness” parameter we haven’t seen with other components: groupName. Select each of the three radio buttons in turn, and verify that each belongs to the same group, syntax, even though each has its own distinct label: Method, Property, and Operator (see Figure 11-23). Note also the empty dynamic text field whose instance name is output. You’re about to wire up the radio buttons to that text field. Figure 11-23. RadioButton instances must be associated with a group name. Click into frame 1 of the scripts layer, and type the following very condensed but interesting ActionScript: rb1.group.addEventListener(Event.CHANGE, changeHandler); function changeHandler(evt:Event):void { output.text = rb1.group.selection.label; }; What makes this interesting? In most of the event-handling samples in this chapter, you’ve invoked the addEventListener() method on an object that you personally gave an instance name. Here, that might have been rb1, but that’s not the focal point in this case. You’re not adding an event listener to a particular radio button but rather to the group to which these buttons belong. The RadioButton class provides a group property, which means that each instance knows to which group it belongs. It’s the group that dispatches the Event.CHANGE event, which occurs when any one of these radio buttons is clicked. It doesn’t matter which radio button’s group property you use, because all of them point to the same RadioButtonGroup instance. The associated function updates the output text field by sending it the 631 www.zshareall.com
  4. CHAPTER 11 selected button in this group—in particular, that button’s label property, which is either Method, Property, or Operator. Note that the Component Parameters area gives you the option to supply a value for each radio button. This allows you to say one thing and do another, just as in the List example. The difference is that the List choices were label and data , and here they are label and value, and the data type of value is typed as Object, not String. The text field wants a string, so you would change that line of ActionScript to output.text = rb1.group.selection.value.toString(); . For example, if you change the value of the Operator RadioButton to Correct, you turn this exercise into a quiz. ScrollPane component The ScrollPane component lets you have eyes bigger than your stomach. If you want to display a super- large image—so large that you’ll need scrollbars—ScrollPane is your component; Figure 11-24 shows it in action. Figure 11-24. ScrollPane provides optional scrollbars to accommodate oversized content. ScrollPane has nested skins because of its scrollbars, so double-clicking an instance during authoring will open its skin elements in tiers. Styling works the same as described in the “Button component” section, although with no text elements, most of your customization work will probably center around skins. 632 www.zshareall.com
  5. BUILDING INTERFACES WITH THE UI COMPONENTS Using one or more instances of the ScrollPane component in your movie will add 21KB to the SWF if no other components share the load. In this example, there’s no need for ActionScript. 1. Open the ScrollPane.fla file in this chapter’s Exercise folder. Select the ScrollPane instance, and click the Parameters tab of the Component Inspector panel. 2. In the Component Parameters area, double-click the right column of the source row. Type Redleaves.jpg. 3. Test the movie. Pretty slick! The source parameter can be pointed to any file format that Flash can load dynamically, including JPEGs, GIFs, PNGs, and other SWFs. Slider component The Slider component is conceptually the same thing as NumericStepper, except that instead of clicking buttons to advance from one number to the next, the user drags a knob along a slider, as shown in Figure 11-25. You, as designer, are responsible for setting the minimum and maximum values, and this component lets you specify whether sliding is smooth or snaps to increments specified by you. Figure 11-25. Slider lets the user drag a handle back and forth to specify a value. Slider has no text elements, so styling is fairly light. What’s there works as it does for the Button component. Skinning also works as it does for Button: double-click a Slider instance in the authoring environment to change the knob and track skins. Using one or more instances of the Slider component in your movie will add 17KB to the SWF if no other components share the load. To see how the Slider component works, open the Slider.fla file in this chapter’s Exercise folder. Note that the instance name for the Slider instance is slider, which works only because ActionScript is a case-sensitive language. You couldn’t call it Slider, because that’s the name of the class that defines this object. Also note the instance names circle1 and circle2 on the two circles. You’re about to wire up the Slider component to adjust their width and height. Click into frame 1 of the scripts layer, and type the following ActionScript: 633 www.zshareall.com
  6. CHAPTER 11 slider.addEventListener(Event.CHANGE, changeHandler); function changeHandler(evt:Event):void { circle1.scaleX = slider.value / 100; circle2.scaleY = slider.value / 100; }; When the Event.CHANGE event is dispatched—this happens as the knob moves along the track—the slider’s value property is used to update scaling properties of the circle movie clips. Why divide by 100? In movie clip scaling, 0 percent is 0 and 100 percent is 1. Because the Slider instance happens to have its maximum parameter set to 100, the division puts value into the desired range, as shown in Figure 11-26. Figure 11-26. A single Slider instance can adjust many objects. Hey, that looks like a face! Be sure to experiment with the parameters in the Properties panel’s Component Parameters area. Most of them are intuitive, but liveDragging and snapInterval might not be. The liveDragging parameter tells Slider whether to update its value property as the knob moves, as opposed to when it is released. When you set liveDragging to false (deselected), the circles will resize only after you reposition the knob and then release it. The snapInterval parameter tells Slider how often to update its value property. To demonstrate, set liveDragging to true (a check mark), and then change snapInterval to a small number, such as 1. When you drag the knob, you’ll see the circles resize smoothly. Change snapInterval to 10 and test again, and the circles resize less smoothly, because you’re asking value to count by tens. You may be surprised to find a direction parameter (its values are horizontal and vertical). Why not just use the Free Transform tool to rotate this slider? Well, try it. We’ll wait...that’s kind of weird, right? It doesn’t work. Components are a sophisticated phenomenon, even though they look so simple. Now, what if you want a slanted slider, not horizontal or vertical? Here’s a trick: select the Slider instance, convert it to a movie clip (Modify ➤ Convert to Symbol), and give that movie clip an instance name such as sliderClip. When both the movie clip and its nested Slider have instance names, you’re set. sliderClip.slider.addEventListener(Event.CHANGE, changeHandler); function changeHandler(evt:Event):void { circle1.scaleX = sliderClip.slider.value / 100; circle2.scaleY = sliderClip.slider.value / 100; }; 634 www.zshareall.com
  7. BUILDING INTERFACES WITH THE UI COMPONENTS TextArea component Chapter 6 introduced you to text fields and containers. Consider the TextArea component a text field in a tux. It has an attractive, slightly beveled border, lets you limit how many characters can be typed into it (like input text fields), and is optionally scrollable (see Figure 11-27). This component is akin to the element in HTML. Figure 11-27. TextArea is the James Bond of text fields. TextArea is skinnable, but the parts are few. You’ll see a nested skin for the scrollbars when you double- click an instance in the authoring environment. More likely, you’ll want to style its text contents, which works as described in the “Button component” section. Using one or more instances of the TextArea component in your movie will add 21KB to the SWF if no other components (other than the automatically included UIScrollBar) share the load. Open the TextArea.fla file in this chapter’s Exercise folder to see an example of populating a TextArea instance with text. (We figured it would be cruel to make you type in a lengthy bit of sample text on your own.) Note that the TextArea component can display HTML text, as shown in the sample file, or plain text. Use the component’s ActionScript htmlText or text properties accordingly. Notice that the Component Parameters tab of the Properties panel shows only a text parameter for supplying text. We can’t imagine anyone using that tiny space to enter more than a sentence, so reference that parameter as a property in your ActionScript. Assuming ta is the TextArea component’s instance name, here’s the code: 635 www.zshareall.com
  8. CHAPTER 11 ta.htmlText = "HTML text here, with styling."; or it could look like this: ta.text = "Plain text content here."; TextInput component The TextInput component is the single-line kid brother of TextArea. For this reason, to trump it up, we’ll show it displaying one of the shortest short stories in the world, attributed to Ernest Hemingway (see Figure 11-28). Figure 11-28. TextInput is a single-line component, mainly used for user input. TextInput is primarily used to collect typed user input, like HTML-based “Contact Us” forms, and can even be set to display password characters as asterisks (see the displayAsPassword parameter). The component is skinnable—just double-click an instance in the authoring environment—but there’s not much to skin. Styling works as described in the “Button component” section. Using one or more instances of the TextInput component in your movie will add 15KB to the SWF if no other components share the load. To see the TextInput component in action, open the TextInput.fla file that accompanies this chapter. Note the two TextInput instances, with instance names input (top) and output (bottom). Select each component in turn, and look at the Parameters tab of the Component Inspector panel as you do. For the top TextInput instance, the displayAsPassword and editable parameters are set to true. For the bottom one, both of those parameters are set to false. You’re about to make the upper component reveal its password to the lower one. Click into frame 1 of the scripts layer, and type the following ActionScript: input.addEventListener(Event.CHANGE, changeHandler); function changeHandler(evt:Event):void { output.text = input.text; }; As text is typed into the upper TextInput instance, the Event.CHANGE handler updates the lower instance’s text content with that of the upper instance’s content. Because of the parameter settings, the text content is hidden above but clearly displayed below. 636 www.zshareall.com
  9. BUILDING INTERFACES WITH THE UI COMPONENTS TileList component TileList is not unlike the ScrollPane component. Both load files for display, optionally with scrollbars, but TileList displays numerous files—JPEGs, SWFs, and so on—in the tiled arrangement shown in Figure 11-29. Double-click a TileList instance to edit its skins. You’ll see a second tier of skins for the scrollbars. Styling may be accomplished as described in the “Button component” section. Using one or more instances of the TileList component in your movie will add 32KB to the SWF if no other components share the load. Figure 11-29. TileList displays a tiled arrangement of content, optionally scrolling as necessary. Quite a few parameters are listed in the Component Parameters area of the Properties panel for this component, but they’re all easy to grasp. For example, there are settings for the width and number of columns, height and number of rows, direction or orientation (horizontal or vertical), and scrolling settings (on, off, and auto, the last of which makes scrollbars show only as necessary). The dataProvider parameter is the most important, because that’s where you define the content to show. It works the same as the dataProvider for ComboBox, except that instead of label and data properties, TileList expects label and source. If you find the Component Parameters a bit confining, you can always use ActionScript to add items to the TileList. To try this, open the TileList.fla file in the Chapter 11 Exercise folder. Note that the 637 www.zshareall.com
  10. CHAPTER 11 TileList instance has the instance name tl, and the dynamic text field below it has the instance name output. Click into frame 1 of the scripts layer, and type the following ActionScript: tl.addItem({label:"Mug 6", source:"Mug06.jpg"}); tl.addItem({label:"Mug 7", source:"Mug07.jpg"}); tl.addItem({label:"Mug 8", source:"Mug08.jpg"}); tl.addEventListener(Event.CHANGE, changeHandler); function changeHandler(evt:Event):void { output.text = tl.selectedItem.label; }; The first three lines use practically the same approach we used for adding an additional item to the ComboBox instance in that section of the chapter. Mugs 1 through 5 are specified in the Properties panel. Here, these three lines of code give us a few more mug shots (heh, mug shots—we love that joke). In the event handler, the changeHandler() function updates the output text fields’ text property with the label value of the TileList’s selected item. TileList also supports multiple selections, like the List component. The sample code in the “List component” section provides the same basic mechanism you would use here, except instead of targeting the data property, you’ll probably want to target label , as shown in the preceding single-selection sample. UILoader component If the Flash CS5 UI components all went to a Halloween party, UILoader would show up as the Invisible Man (see Figure 11-30). Figure 11-30. Practically speaking, UILoader has no visual elements (and yes, this figure is empty; being able to include it cracks us up). 638 www.zshareall.com
  11. BUILDING INTERFACES WITH THE UI COMPONENTS So, what’s the point? Ah, but UILoader is such a selfless, giving component! Its purpose is to load and display content other than itself. This lets you avoid using the Loader class (which you’ll encounter in Chapter 14), just in case the thought of ActionScript makes you feel like you discovered half a worm in your apple. Simply enter a filename into the source parameter of the Properties panel’s Component Parameters area, and you’re set (see Figure 11-31). Figure 11-31. Just enter in the name of a supported file format, and Flash will load it. Using one or more instances of the UILoader component in your movie will add 15KB to the SWF if no other components share the load. Here’s a UILoader component exercise: 1. Open the UILoader.fla file that accompanies this chapter. Double-click the UILoader instance, and you’ll see message that no skins are available. Since we aren’t speaking to this component with ActionScript (yet), it doesn’t need an instance name. 2. In the Parameters tab of the Component Inspector panel, enter the filename Redleaves.jpg into the right column of the source row. This references a JPG file in the same folder as your FLA. 3. Test your movie, and you’ll see the leaves load into its UILoader container. 4. Deselect the maintainAspectRatio parameter and test again. This time, the image loads a bit squished. Our personal preference is usually to maintain aspect ratio. The scaleContent parameter determines whether the loaded content is scaled or cropped in its container. 639 www.zshareall.com
  12. CHAPTER 11 5. Our friend ProgressBar is about to make a cameo appearance. Drag an instance of the ProgessBar component to the stage below the UILoader instance, and give the UILoader instance the instance name loader. 6. Select the ProgressBar instance, and in the Parameters tab, set its source parameter to loader—that’s the instance name you just gave the UILoader instance (see Figure 11-32). You’re associating the two and telling the ProgressBar component to check with the UILoader component to divulge how much of the requested file has loaded. This book was purchased by flashfast1@gmail.com Figure 11-32. It’s very easy to show the load progress for a UILoader instance. 7. Test your movie again. 8. In the SWF’s menu bar, select View ➤ Simulate Download to see some super-easy preloading action. 9. Close the SWF. 10. To wrap up, let’s add a teensy bit of ActionScript. (Don’t worry, that half a worm we mentioned earlier was just a centipede—half a centipede.) To make sure ActionScript talks to the ProgressBar instance, give it an instance name. We’re using pb. Click into frame 1 of the scripts layer, and type the following ActionScript: pb.addEventListener(Event.COMPLETE, completeHandler); function completeHandler(evt:Event):void { removeChild(pb); }; 11. Test the movie for the last time. You’ll see what this ActionScript does: it makes the progress bar disappear when loading is complete. 640 www.zshareall.com
  13. BUILDING INTERFACES WITH THE UI COMPONENTS UIScrollBar component If you read any other sections of this chapter, you’ve probably already been introduced to the UIScrollBar component. This component is a humble but useful member of the team, because it allows other components to have scrollbars. UIScrollBar is skinnable by double-clicking any instance in the authoring environment. Styling doesn’t make much sense, but it is possible as described in the “Button component” section. Using one or more instances of the UIScrollBar component in your movie will add 18KB to the SWF if no other components share the load. So as to avoid repeating ourselves, we’ll direct your attention to the “Using the UIScrollBar component” section in Chapter 6 to see this component in action. What you have learned In this chapter, you learned the following: How to use every one of the Flash CS5 UI components How to write the ActionScript that controls components How to skin a component How to manage components in a Flash movie Clients are fickle. One day the black Times Roman they asked for is fabulous, and the next day it “just has to be” green Helvetica Narrow. This can be a huge waste of time. They start with one image and suddenly there are 100. You can spend hours opening Flash files and physically making the changes, or pawing through ActionScript looking for code that formats text or handles the images. Is there an easier way? XML. We have been talking about it throughout this book, and the time has arrived for you to explore XML’s powerful relationship with Flash. Intrigued? Turn the page. 641 www.zshareall.com
  14. www.zshareall.com
  15. Chapter 12 XML (Dynamic Data) To this point in the book, we have dangled the use of XML in front of you with no real explanation of how it works. That time has arrived. Flash is a social creature. Not only does it rub elbows with HTML—coexisting happily with text, JavaScript, images, audio, video, CSS, and more—but it can also reach out past its own SWF boundaries to collaborate with data hosted on a server. In the hands of an experienced programmer, Flash can interact with database applications by way of the URLLoader and URLVariables classes, perform web service and Flash remoting calls, and even slap a secret handshake with Ajax, thanks to the ExternalInterface class. All this from a browser plug-in that began its life as a way to improve on animated GIFs! It’s easy to see why Flash has become a widespread phenomenon, and its versatility makes equally social creatures of the countless designers and developers who end up warming their diverse mitts around the same campfire because of it. This book isn’t here to make programmers out of artists. We don’t have the page count to delve into most of the concepts just mentioned, but we are going to introduce you to a markup language called XML that, with a bit of help from ActionScript, can make your SWFs dynamic. Here’s what we’ll cover in this chapter: Retrieving and filtering XML data using E4X syntax Using retrieved data in collaboration with ActionScript The following files are used in this chapter (located in Chapter13/ExerciseFiles_Ch13/Exercise/): 643 www.zshareall.com
  16. CHAPTER 12 LoadXML.fla flashBooks.xml LoadXML-E4XBonusRound.fla CopyMotion.fla CopyMotion.xml XFLexercise.fla The source files are available online at www.friendsofED.com/download.html?isbn=1430229940. If you haven’t already worked with XML, we bet our next single malt Scotch you’ve at least heard of it. The letters stand for eXtensible Markup Language, and extensibility—the ability to create your own HTML-like tags—is almost certainly the reason XML has become a towering champ in data communication. Countless markup languages and file formats are based on XML, including SMIL, RSS, XAML, MXML, RDF, WAP, SVG, SOAP, WSDL, OpenDocument, XHTML, and so on—truly more than would fit on this page. We’ll leave the letter combinations to a Scrabble master. “That’s fine and dandy,” you might be saying, “but, guys, what is XML?” Fair enough. The remarkable thing about this language is that it can basically be whatever you want it to be, provided you stick by its rules. The W3C defines the syntax recommendation for XML (XML 1.0, fifth edition, which is the latest at the time this book was written) at www.w3.org/TR/2008/REC-xml-20081126/. The main purpose of XML is to let you share data. In fact, XML is so flexible that newcomers are often baffled about where to even begin. On paper—or rather, on the screen—XML looks a lot like another famous W3C specification: HTML. However, rather than using the predetermined tags and attributes supplied by HTML, XML lets you organize your content into descriptive tags of your own design. While HTML formats data for display, XML actually describes data. The combination of familiar, hierarchical format and completely custom tags generally makes XML content easy to read, both to computers and to humans. By separating your data from the movie, you give yourself the opportunity to change content from the outside, affecting SWFs without needing to republish them. In a minute you are actually going to write the following XML: If you are new to this language, we’ll bet you looked at it and thought, “Has something to do with a bunch of Flash books.” You are correct, and that’s the beauty and simplicity of XML. There is nothing here about formatting text or any other stuff. All it does is present data—a list of Flash books. So, are you ready to write some XML? 644 www.zshareall.com
  17. XML (DYNAMIC DATA) Writing XML Here’s a typical scenario. One of the authors has a rather extensive collection of Flash books in his office. The collection expands and contracts based upon the current version of Flash, and he thinks it would be rather neat to keep a running inventory of his collection. Rather than list all 50 or 60 of them, he decides to start out with 5 core titles and grow from there. The reason for the 5 titles is simple: if he can get 5 books organized, then it is no big deal to get 50, 500, or even 5,000 books into the document. The decision is to start with books from friends of ED, and he decides to start with: ActionScript 3.0 Image Effects, Flash Applications for Mobile Devices, ActionScript for Animation, Foundation ActionScript 3.0, and Flash Math Creativity. Each book has its own page count, author, and publisher. Where to begin? Let’s take a look. Every XML document must have at least one tag, which constitutes its root element. The root element should describe the document’s contents. In this case, we’re dealing with Flash books, so let’s make that our root: The rest of our elements will stack themselves inside this first one. Every title is its own book, so we’ll add five custom elements: Again, these tag names aren’t things that exist in XML. It’s up to you to decide which elements make sense for the data at hand, to name those elements accordingly, and then to use them. Note that each opening tag has a closing tag partner (with a slash in it), which is a characteristic required by the XML standard. If an element doesn’t contain further data inside it, that element can optionally serve as its own opening and closing tags. In such a case, the pairing would look like this: . But here, each book has a title, so these elements will remain as tag pairs. 645 www.zshareall.com
  18. CHAPTER 12 The next step—adding a title—seems obvious enough: ActionScript 3.0 Image Effects Flash Applications for Mobile Devices ActionScript for Animation Foundation ActionScript 3.0 Flash Math Creativity The difference here is that the tags contain textual data instead of additional elements, but you get the idea. Hold on a minute—all of these tags contain data! The tags contain text nodes (that is, nonelement text content), and the and tags contain XML element nodes (that is, descriptive tags). It doesn’t take much effort to connect the rest of the dots. An excerpt of the completed document might look something like this: Flash Applications for Mobile Devices friendsofED 663 pages . . . Actually, that isn’t complete after all, is it? The author is missing. The thing about these books is there may be one author on the cover or a number of authors on the cover. For that, another tier of elements is in order: Flash Applications for Mobile Devices friendsofED 514 pages 646 www.zshareall.com
  19. XML (DYNAMIC DATA) Richard Leggett Weyert de Boer Scott Janousek . . . That would certainly do it. The tag names are meaningful, which is handy when it comes time to retrieve the data. The nested structure organizes each concept into a hierarchy that makes sense. Nicely done, but in a sizable collection, this particular arrangement might come across as bulky. Is there a way to trim it down? Sure thing. Remember that XML allows you to create your own attributes, so you have the option of rearranging the furniture along these lines: Richard Leggett Weyert de Boer Scott Janousek . . . The exact same information is conveyed. The only difference now is that some of the data has been shifted to tag attributes, or attribute nodes, rather than tags. HTML provides the same mechanism, by the way. Consider the src attribute of an tag (). All it does here is change how the data would be retrieved, as you’ll see in the “Using E4X syntax” section of this chapter. Which approach is better? Honestly, the choice is yours. It’s not so much a question of “better” as it is what best matches your sense of orderliness. Ironically, this open-ended quality, which is one of XML’s strongest assets, is the one feature that is the hardest for those who are new to the subject to grasp. It doesn’t have to make sense to anyone but you. Working with and structuring an XML document follows the first principle of web development: “No one cares how you did it. They just care that it works.” Find what works best for you, because in the final analysis, your client will never pick up the phone and say, “Dude, that was one sweetly structured XML document you put together.” Having said that, if you are part of a collaborative work group, be sure that everyone involved agrees on terminology before you start. Folks, this is a bit like a ceramics class. As long as you’re careful around the kiln, no one can tell you whose vase is art and whose isn’t. Just work the clay between your fingers, let a number of shapes mull 647 www.zshareall.com
  20. CHAPTER 12 around your mind, and then form the clay into a structure that appeals to you. While you’re at it, keep a few rules in mind: If you open a tag, close it (). If a tag doesn’t come in two parts—that is, if it contains only attributes, or nothing at all—make sure it closes itself (). Close nested tags in reciprocating order ( is correct, but will “blow up”). Wrap attribute values in quotation marks or single quotation marks (, ). The flashbooks example we just discussed would be saved as a simple text file with the .xml file extension, as in flashBooks.xml. In fact, it isn’t a bad idea, once you have finished writing your XML document, to open it in a browser like Firefox to see whether there are any problems. Now that our introductions have been made, let’s get social. Feel free to use a text editor such as Notepad on Windows or TextEdit on the Mac to create your XML files. Just be sure you add the .xml extension to the file’s name. If you have Dreamweaver CS5, that’s even better, because it automatically writes the document declaration for you at the top, and it offers tools such as code completion to speed up your workflow. Also, keep in mind that manually writing XML is just one approach. As you start becoming more comfortable with using XML, you will eventually find yourself drifting toward server-side scripting—such as PHP—to handle complex data management. Loading an XML file XML in Flash has had a rather rocky relationship simply because, until a couple of years ago, it was right up there with beating yourself in the head with a brick. Things have changed, significantly for the better. The ActionScript required for loading an XML document isn’t complicated. You’ll need an instance of the XML and URLLoader classes, and, of course, an XML document. In our case, the document will always be an actual XML file, although XML documents can be built from scratch with ActionScript. Open the LoadXML.fla file that accompanies this chapter. Click into frame 1 of the scripts layer, and open the Actions panel to see the following code: var xmlDoc:XML = new XML(); var loader:URLLoader = new URLLoader(); var req:URLRequest = new URLRequest("flashBooks.xml"); loader.load(req); 648 www.zshareall.com
Đồng bộ tài khoản