Getting Started with Flex - Foundation ActionScript 3, Second Edition (2014)

Foundation ActionScript 3, Second Edition (2014)

Chapter 13. Getting Started with Flex

This chapter covers the following topics:

· What Flex is and how it relates to Flash

· How to install and use the Flex SDK

· How to install and use Flash Builder 4.7

· How to create a simple Flex application with both the Flex SDK and Flash Builder

Before you dig into this chapter, I have a confession to make: there isn’t enough space in this book to teach you everything there is to know about Flex. It’s not all bad, though. Instead of trying to cover the entire world of Flex in a couple chapters, I’m going to show you enough of Flex to give you a comfortable grounding and get you started.

If you decide that you want to go ahead and master Flex 4, Apress has just the book for you: AdvancED Flex 4 by Shashank Tiwari and Elad Elrom (ISBN 978-1-4302-2483-9).

Introducing Flex

Put simply, Flex is a family of products that makes it easier for developers to create so-called rich Internet applications (RIAs).

If you think back to the discussion of Flash ActionScript 3.0 components in Chapter 9, you’ll recall that it took quite a bit of work to create a relatively simple application. The components were designed to be easy to skin and use streamlined code so movies would not have as much overhead and would load more quickly. A lot of the complexity in the previous version of the Flash components was removed for these reasons.

Flex, on the other hand, has been designed from the ground up with application development in mind. The components are more robust, and Flex has a large framework of classes designed to manage more complex graphic user interfaces (GUIs). The Flex framework is heavier than its Flash sibling’s framework, it’s not quite as easy to configure graphically, and it doesn’t have a timeline to create more expressive content natively (although you can import other SWFs for that purpose). But Flex blows everything else away if you want to create desktop-style applications on the Internet.

Understanding Rich Internet Applications

The term rich Internet application is bandied about a lot at the moment, but it’s hard to find a concrete definition of what an application must have or do to qualify as an RIA. In lieu of anything more official, I’m going to tell you what I think defines an RIA.

Macromedia (now Adobe) invented the term rich Internet application back in March 2002, giving a name to a concept that had already existed for some time under various guises. The concept is a simple one: an application that is delivered over the Internet but behaves more like a desktop application.

Instead of the traditional web application model (client-server model), where all the data and processing are held on the server and what you see in your web browser is just a static representation of the data, RIAs handle some of the data and processing themselves. This means that they can give the user instant feedback on operations, rather than needing to wait for the server to respond.

The ability to process data on the client and give the user instant feedback also means that some of the idioms traditionally found in desktop software can be re-created on the Web. Features such as drag-and-drop, table sorting, and tree controls are all common in the latest crop of RIAs.

Meet the (Flex) Family

As I mentioned earlier, Flex is not a single product. Rather, it’s a family of products and technologies that work together to give you the platform to create truly engaging RIAs.

The Flex Framework

The most important part of Flex is the Flex framework, which is a collection of ActionScript 3.0 classes on top of which applications are built. When you hear developers talking about how Flex is great, they’re usually talking about the Flex framework. It is the primary reason that application development is so quick and easy with Flex.

The Flex framework classes include UI components (buttons, data grids, and so on), layout containers, data formatting and validation libraries, and a whole lot more. The next chapter explores a number of parts of the Flex framework to give you a taste of what Flex is all about.

The Flash Player

Flex is part of the Adobe Flash Platform, which is a collection of technologies with the Flash Player at its core. This means that users don’t need to download yet another browser plug-in to view your applications—they just need the most up-to-date Flash Player. More than 90 percent of regular web users have a recent version of the Flash Player installed. That’s more than enough to start developing Flex applications targeted at the wider Internet population (and not just us web geeks).

Targeting the Flash Player also means that your applications will be cross-platform out of the box, opening your application to audiences on Windows, Mac OS X, and Linux without you having to lift a finger. And that’s nice.

One downside of the reliance of the Flash Player is that your applications will run within a security sandbox and won’t be able to write to files on the local file system. For this reason, Flex applications tend to be distributed, where data is stored on a central server and accessed over the Internet. This need not dash any of your hopes of writing the next version of Microsoft Word as a Flex application, though. Adobe AIR provides a runtime environment for your Flex applications that has access to the local file system. See the “Adobe AIR” section coming up shortly for more information about this capability.

MXML

ActionScript 3.0 may well be perfect for providing the functionality of a Flex application, but it’s not the ideal medium for creating UIs. If you’ve ever had to use the Document Object Model (DOM) in JavaScript to create HTML elements, you have some idea of how painful creating UIs using ActionScript 3.0 can be.

Thankfully, Flex includes an XML-based markup language called Multimedia Extensible Markup Language (MXML), which provides a structured way to define your UIs. You can think of MXML as the XHTML of the Flex world. In fact, the relationship between MXML and ActionScript is a direct correlation to the way XHTML and JavaScript work together. Further, MXML allows you to lay out your application and specify its various states, as well as how and when to transition between those states.

Having said all that, MXML is about more than just UIs. You can also include script and style blocks to determine the behavior and appearance of your applications. Script blocks can either contain ActionScript 3.0 code or link to external ActionScript 3.0 files. Style blocks use CSS syntax to define styles for interface controls, and like the script blocks, can either contain the style data or link to an external CSS file.

You can also create nonvisual objects that link to web services or other external data sources, and use the magic of data binding to render the data using the UI components included as part of the Flex framework. In fact, using the HTTPService class and data binding, you could create a Flex application that consumes a web service (such as a Flickr photostream) and display the data to the user without needing to write a single line of ActionScript 3.0 code!

The Flex Software Development Kit

Once you have your ActionScript 3.0 and MXML files, you’ll need something to turn those files into an SWF file that can be loaded into the Flash Player. The Flex Software Development Kit (SDK) includes the entire Flex framework, the mxmlc compiler for compiling Flex applications, the compc compiler for compiling components, and a command-line debugger to help you root out problems in your applications.

The Flex SDK is free for both commercial and noncommercial purposes, and is available from the Adobe website (http://www.adobe.com/devnet/flex/flex-sdk-download.html). It contains everything you need to start writing Flex applications today, and without spending a single penny. Now that’s what I call a bargain.

Adobe donated Flex to the Apache Software Foundation in 2012 to ensure continued development and success of Flex as a community-driven open source project. For the latest information on Apache Flex, visit their website (http://flex.apache.org).

Later in the chapter, in the “Building your first Flex application” section, you’ll build a simple application using the Flex SDK so you can see how to use the compiler.

Flash Builder

Creating and maintaining large applications using nothing but a text editor and the Flex SDK is perfectly acceptable, but it’s not the most efficient use of your time.

Flash Builder is an integrated development environment (IDE), like Flash CC. Flash Builder is specifically designed to help you build Flex applications more quickly and easily than if you were using the simple tools provided as part of the SDK. It includes a visual interface builder that makes it easy to create and edit the MXML files for your interfaces, a code editor that understands both MXML and ActionScript 3.0 code, and an integrated debugger to help you find and fix bugs within applications.

If you want to use Flash Builder, you’ll need to purchase a license from Adobe, but you can download the free 30-day trial from http://www.adobe.com/products/flash-builder.html if you just want to play around.

To demonstrate how much simpler it is to create applications with Flash Builder as opposed to the Flex SDK, you’ll create the same application using both tools.

Adobe LiveCycle DS

LiveCycle DS, formerly Flex Data Services (not to be confused with LiveCycle Enterprise Suite) is an enterprise-level product that makes it easy for your application to communicate with a central server and vice versa. Distributed RIAs (applications that store data on a central server) require a middle tier to act as an intermediary between the data store (probably a database) and the application itself, and LiveCycle DS helps fill this role.

LiveCycle DS isn’t the only option for the middle tier of a distributed RIA. You could use PHP, ASP, or any number of other server-side programming languages to roll your own, or even use a third-party solution.

The services that LiveCycle DS provides include data synchronization, automatic paging of results, the ability to push data from the server to the application, and collaborative features.

If you’re interested in exploring Flex Data Services, you can download the free LiveCycle DS Express and find out more information about it on the Adobe website (http://www.adobe.com/products/livecycle.html). There is also an open source counterpart to the LiveCycle technologies known as BlazeDS (http://opensource.adobe.com/wiki/display/blazeds/BlazeDS/).

The data services discussion is way out of scope for this introductory look at Flex. However, if you are seeking a more thorough explanation of these products, check out http://gregsramblings.com/2008/03/27/livecycle-ds-vs-livecycle-es-clearing-up-the-confusion/ or consider picking up a copy of AdvancED Flex 4.

Adobe AIR

The final part of the Flex puzzle is Adobe AIR (the acronym stands for Adobe Integrated Runtime, and yes, that means its full title is the redundant Adobe Adobe Integrated Runtime), which is a cross-platform runtime environment for both desktop (Windows, Mac OS X, and Linux) and mobile devices (iOS and Android), reaching over a billion desktop systems and mobile app stores for over 500 million devices.

AIR allows you to build and deploy RIAs using a mixture of Flash CC, Flex, HTML, JavaScript, and PDF files that can be installed and run from the user’s desktop or mobile device rather than their web browser. In addition to allowing RIAs to run on the desktop, an AIR application has full access to the local file system and is able to integrate with features of the host operating system such as the clipboard, windowing system, and the network API.

AIR is available for free, meaning that anyone can create desktop applications using Flex without spending any hard-earned cash. Consider it an early or late birthday present from Adobe (unless it’s actually your birthday today, in which case, happy birthday).

Getting Started with the Flex SDK

In this section, you’ll get you up and running with the Flex SDK. First you’ll download and install the SDK, and then you’ll create your first Flex application.

Installing the Flex SDK

The Flex SDK is available as a free download from the Adobe website. Go to http://www.adobe.com/devnet/flex/flex-sdk-download.html and click the Flex SDK link to download the Flex SDK.

Once the .zip file has downloaded, you’ll need to extract the contents to a sensible location on your computer. The steps to do this differ greatly depending on which operating system you’re using, so follow the steps under the appropriate heading in this section.

Windows

If you’re using Windows, first extract the contents of the Flex SDK .zip file into a folder named flex in the root of your C: drive. Next, add the c:\flex\bin directory to the system path, as follows:

Image Note On Windows 8, this information is found through Settings image Control Panel image System and Security image System image Advanced System Settings. You’ll then see the Environment Variables button and can follow the instructions from Step 2.

1. From the Start menu, right-click My Computer and select Properties.

2. In the System Properties dialog box, select the Advanced tab, as shown in Figure 13-1. Click the Environment Variables button.

image

Figure 13-1. The Advanced tab of the System Properties dialog box

3. Under System variables, scroll down the list until you find an entry for Path, select that entry, and then click the Edit button.

4. In the Edit System Variable dialog box, shown in Figure 13-2, scroll to the end of the text in the list box under System variables and add ;c:\flex\bin to the end. Don’t omit the semicolon at the beginning—it’s used to separate multiple values for the Path variable, and without it you won’t be able to use the mxmlc compiler.

image

Figure 13-2. Adding the c:\flex\bin directory to the system path

5. Click OK in all the open dialog boxes to accept the changes you’ve made.

6. To test that everything worked, open the Command Prompt window by selecting Start image All programs image Accessories image Command Prompt. In the window, type mxmlc, and then press the Enter key. You should see the output shown in Figure 13-3.

image

Figure 13-3. Verifying that mxmlc is installed on Windows

If you got a message saying that mxmlc is not a recognized command, try repeating the preceding steps.

Mac OS X

If you’re using Mac OS X, follow these steps to install the Flex SOFTWARE DEVELOPMENT KIT (SDK):

1. Extract the contents of the Flex SDK .zip file into a folder named flex in your home folder.

2. Open a Terminal window by double-clicking the Terminal.app file in the Applications folder within the Utilities folder.

3. If you’re using Mac OS X 10.2 or earlier, type the following line, and then press Return:

echo 'setenv PATH ~/flex/bin:$PATH' >> ~/.tcshrc

If you’re using Mac OS X 10.3 or later, type the following line, and then press Return:

echo 'export PATH=~/flex/bin:$PATH' >> ~/.bash_profile

4. To test that the change has taken effect, quit and reopen Terminal.app, type mxmlc, and press Return. You should see output showing that the mxmlc compiler is installed.

If you got message telling you the mxmlc command could not be found, try repeating the preceding steps.

Linux

If you’re using a Linux distribution on a daily basis, you probably know better than I do where you want to put your downloaded applications. I suggest somewhere like /usr/local/flex, but feel free to extract the files wherever you choose. Once that’s done, all you need to do is to edit your .profile file and add the /usr/local/flex/bin directory to the PATH environment variable, or whatever the equivalent is for the shell you’re using.

Finding a Suitable Editor

After you have the Flex SDK installed, you’ll need a text editor to edit the ActionScript 3.0 and MXML files. You have several options, depending on whether you’re using Mac OS X or Windows as your operating system of choice.

If you’re using Microsoft Windows, I suggest a great open source editor called FlashDevelop, which is designed specifically for working with Flash and Flex projects. Download it from http://www.flashdevelop.org. Be sure to download and configure the extras for ActionScript 3.0 and MXML code completion, as explained on the site.

For Mac OS X, I recommend SE|PY or Eclipse. Of the two, SE|PY offers a more robust toolset, similar to that of FlashDevelop. But because Eclipse is actually the technology Flex is built on, choosing Eclipse will allow you to make more advanced customizations to the interface.

Another great IDE that supports Flash and AIR development is IntelliJ IDEA by JetBrains. Functional cross platform, IntelliJ IDEA runs on Microsoft Windows, Mac OS X, and Linux operating systems and is ideal for ActionScript and MXML with on-the-fly code analysis, completion, navigation, advanced refactorings, code generation, UML diagrams, UI designer, interactive debugger, and profiler.

Building your first Flex Application

As I mentioned earlier, you’re going to create a simple application using the Flex SDK, and then re-create it later in the chapter using Flash Builder. It’s worth following this tutorial through, even if you plan on using Flash Builder to create all your applications, because I’m going to cover some basic information about the Flex framework and MXML here that won’t be repeated later.

The application you’re going to create is a reader for the blog on the Adobe Labs website. Oh, and you’re going to do it without writing a single line of ActionScript code, just to show off how powerful MXML can be. The end result is going to look something like Figure 13-4.

image

Figure 13-4. The RSS reader you’ll build

The layout has a table containing all the items from the RSS feed of the Adobe Labs blog, with the summary of the selected item shown in the area below. The two areas are separated by a draggable divider, so that users can decide how much space they want to give to the listing and to the summary.

So, let’s build the RSS reader.

1. Decide where you want to keep your projects. If you have been moving progressively through this book, you probably have created project directories for each chapter. You can do the same here and create a Chapter 13 directory. Wherever you choose to create your projects, create a new directory within it named RSSReader.

2. Within the RSSReader directory, create two subdirectories, named src and bin.

Although step 2 isn’t strictly necessary, it’s good to keep your files organized in this way. The src directory will contain any MXML and ActionScript 3.0 files. The final SWF file will be output into the bin directory. In larger applications, you might also havecomponents, libraries, and assets directories containing other files related to the project.

3. Fire up your chosen text editor, create a new blank file, and save it in the src directory with the name RSSReader.mxml.

4. Now you can start writing the MXML for your RSS reader application. Because MXML is a type of XML, you need to start the MXML file with the XML declaration.

<?xml version="1.0" encoding="utf-8"?>

The version attribute specifies the version of the XML specification that this document uses. Since there is only one version of XML at this time, the value of this attribute will be 1.0. The value of the encoding attribute signifies the character encoding used in the MXML file. In this case, you’ve used utf-8, since that character set supports all characters in all countries throughout the world (you do need to make sure your code editor is able to save UTF-8 encoded files).

If all this character-encoding stuff sounds like complete nonsense, then count yourself lucky—you’re not quite a geek yet. The short version goes something like this: when characters are stored in a computer, they are stored as numbers, and determining which number is used for a particular character is the job of the character encoding.

Many different character encodings are available, but you’re likely to come across only two of them in Flex development: ISO-8859-1 and UTF-8. Of those two, only UTF-8 properly supports multilingual content.

Of course, in order to translate those numbers back into their respective characters, somehow you need to include information about which character encoding is used, and that’s what the encoding attribute of the XML declaration is all about.

5. Next, add the root element for the MXML document. When creating Flex applications, this will always be an <mx:Application> element:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
</mx:Application>

This is the root tag of the MXML document, much like the <html> tag in an XHTML document. The xmlns:mx attribute is required by the XML standard, and it basically uniquely identifies the mx namespace that the Flex framework uses. These namespaces are similar to the namespaces in ActionScript 3.0. You need to make sure you get the value of this attribute right, or you’ll upset the mxmlc compiler.

6. You’re now at the stage where you have a perfectly valid Flex application. It doesn’t actually do anything, but that’s beside the point. Let’s make sure everything is OK before moving on by compiling the application using the mxmlc command-line compiler. Open aCommand Prompt window (Windows) or Terminal window (Mac) and navigate to the RSSReader directory you created in step 1.

7. In Windows, type the following line, and then press Enter:

mxmlc src\RSSReader.mxml -output=bin\RSSReader.swf

In Mac OS X or Linux, type the following line, and then press Enter or Return:

mxmlc src/RSSReader.mxml -output=bin/RSSReader.swf

Make sure there are no errors.

8. Open the RSSReader.swf file in the bin directory with your web browser. You should see absolutely nothing but a blue-green gradient background.

9. If you got all that working, it’s time to add the remainder of the MXML in the RSSReader.mxml file. We won’t go over every little detail here; you’ll explore more details of MXML tags in the next chapter. But have a look and see if you can get a general feel for how the structure of the MXML translates into the UI shown in Figure 13-4. I’ve added some comments to help you.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical" creationComplete="feed.send()">
<!-- The HTTPService item is used to load the RSS data from -->
<!-- the specified URL -->
<mx: HTTPService id="feed" url="http://blogs.adobe.com/labs/feed"/>
<mx:VDividedBox width="100%" height="100%">
<!-- DataGrid control populated with entries from the feed -->
<!-- using data binding -->
<mx:DataGrid id="entries" dataProvider="image
{feed.lastResult.rss.channel.item}" width="100%" height="66%">
<mx:columns>
<mx:DataGridColumn dataField="pubDate" headerText="Date"/>
<mx:DataGridColumn dataField="title" headerText="Title"/>
</mx:columns>
</mx:DataGrid>
<!-- TextArea control bound to the description property of -->
<!-- the selected item from the entries DataGrid -->
<mx:TextArea htmlText="{entries.selectedItem.description}" image
width="100%" height="34%"/>
</mx:VDividedBox>
</mx:Application>

Basically, what you have here is an HTTPService object with an ID of feed that fetches the RSS data from the Adobe Labs website and stores it. This information is displayed in the DataGrid using the magic of data binding, which essentially means that whenever the data source is updated, any component bound to that data source will automatically be updated. The same technique is used to show the description of the currently selected item in DataGrid in the TextArea control.

10.Return to the Command Prompt window (Windows) or Terminal window (Mac). You should still be in the RSSReader directory. In Windows, type the following line, and then press Enter:

mxmlc src\RSSReader.mxml -output=bin\RSSReader.swf

In Mac OS X or Linux, type the following line, and then press Enter or Return:

mxmlc src/RSSReader.mxml -output=bin/RSSReader.swf

Make sure there are no errors.

If opening the SWF directly produces an error, then open in a browser.

11.Open the RSSReader.swf file in the bin directory with your web browser. You should see something like Figure 13-4. If you got a bunch of funny-looking errors instead, ­double-check your MXML file with the one provided in the files you downloaded for this chapter from the friends of ED website.

Now that you’ve worked with the free Flex SDK, let’s turn our attention to the commercial Flex IDE—Flash Builder.

Getting Started with Flash Builder

Installing Flash Builder is a no-brainer. For both Windows and Mac OS X, a lovely installer wizard guides you through the process. All you need to do is to download the installer from the Adobe website at http://www.adobe.com/products/flex/flexbuilder (again, registering if necessary), and then double-click the installer file once it has downloaded to begin the installation.

Understanding the Flash Builder Interface

Flash Builder is a powerful IDE for Flex applications, built on top of the Eclipse open development platform (http://www.eclipse.org). It’s available both as a stand-alone application and as a plug-in for the Eclipse IDE. Unfortunately, this power means that Flash Builder isn’t the easiest of applications to get comfortable with, although if you use Eclipse for other types of projects, using it for Flex will be a natural transition. If you have never used Eclipse, it can be a bit of a daunting environment. Thankfully, the first thing you see when you launch the application is the Flex Start Page, which contains links to samples and tutorials to get you started, as shown in Figure 13-5.

image

Figure 13-5. The Flex Start Page appears when you first start Flash Builder

Building your first Flash Builder Application

As I mentioned earlier, you’re going to create the same RSS reader application as you just did with the Flex SDK but do it Flash Builder style. You’ll still need to get your hands dirty with a bit of manual MXML authoring, but by the time you’ve finished this example, the benefits of having a fully integrated IDE over the simple SDK should be clear.

Creating a new Flex Project

You begin by creating a new project in Flash Builder:

1. Select File image New image Flex Project from the main menu. This will launch the New Flex Project wizard.

The first screen of the wizard allows you to name your project and set the directory location of your project. You’re also given the choice to create a Flex or an AIR application and select your desired server-side technology.

2. Enter RSSReader as the project name, as shown in Figure 13-6. Be sure to set Application Type to Web. If you would like, use the Browse button to set your project’s location to the default working directory for this book’s projects. Click Next.

image

Figure 13-6. Naming a new Flex project

You could have also clicked Finish on the Create a Flex Project screen. This would have loaded a new Flex project with all of the default settings. However, for this example we will take the long route (well, it’s not that long) to show you more options for setting up customized Flex projects.

The first of these options, shown in Figure 13-7, allows you to select the Application server type and output directory of your Flex project. The contents of this directory will ultimately be uploaded to a web server. For now, the default setting is sufficient.

image

Figure 13-7. The Configure Output screen of the New Flex Project wizard

3. Click the Next button.

The final screen in the New Flex Project wizard (see Figure 13-8) lets you set the build paths for your project. You can change many of your project’s default settings:

· The Source path tab allows you to define additional source paths to be used in your application. This will aid in the organization of projects, especially across teams.

· The Library path tab allows you to link to additional programming libraries to be used in your application. For example, you may want to use a third-party ActionScript data processing library.

· By default, both MX Halo (Flex 3) and Spark (Flex 4) component sets are included in the project. In some scenarios, you may want MX only such as when working on an existing Flex 3 project.

· By default, Flex framework linkage uses dynamic linking rather than compiling all classes into the application SWF file (static linking). Dynamic linking produces smaller SWFs, which download faster; however, use more memory because all framework classes are loaded from the runtime shared library (RSL). Runtime shared libraries externalize common assets from SWF files, eliminating the need to download classes repeatedly, which is useful when developing numerous applications that use the same components or symbols.

· To ensure runtime shared libraries loaded from a different domain may be trusted, Flash Player reads the bytes of the incoming RSL and computes a one-way hash, or digest. When Verify RSL digests is enabled, this hash must match the hash generated at compile time. This is recommended for production apps.

· Remove unused RSLs removes unused libraries at compile time to optimize download.

· Use local debug runtime shared libraries when debugging uses local RSLs when debugging an application, which allows stepping into debug RSL files.

· Automatically determine library ordering based on dependencies enables Flash Builder to determine the order to load libraries. To customize library order, disable this option and use the up and down buttons to specify a library order.

· Main source folder is the source folder that exists within your application directory. This folder will contain most of the code files that you will work on with your project.

· Main application file is the primary MXML file that is used for your project. Currently we have been using RSSReader.mxml. However, there are situations when you may want to change this.

· Output folder URL allows you to set the remote location for output of your web application. This lets you output directly to the web server.

image

Figure 13-8. Use this screen to set the build paths.

4. Click the Finish button to begin working on your Flex project.

You’ll now see your new RSSReader project in the Navigator panel in the top left of the Flash Builder 4.7 interface, as shown in Figure 13-9.

image

Figure 13-9. The RSSReader.mxml file generated by Flash Builder’s new Flex project template

The bin-debug directory is where the final SWF file will be stored, and that directory also contains a variety of SWF, JavaScript, and HTML files to make it easy for you to deploy your Flex applications with a minimum of fuss. The JavaScript and HTML files are generated from templates in the html-template directory.

The RSSReader.mxml file has been created and opened in the MXML editor panel, as shown in Figure 13-9, ready for you to start building the application.

Working with MXML Source

Before you add any components to your application, you need to configure the main mx:Application container to lay out its children vertically:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
</mx:Application>

The first component you need to add to your application is a VDividedBox control. The VDividedBox control lays out items vertically with a drag bar between them, allowing the user to resize the height of the items. Enter 100% for both width and height:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
<mx:VDividedBox width="100%" height="100%">

</mx:VDividedBox>
</mx:Application>

Next, add a DataGrid control nested inside the VDividedBox with a height of 66%, and a TextArea control with a height of 34%. This means that the TextArea component will be inserted below the DataGrid component in the VDividedBox component.


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
<mx:VDividedBox width="100%" height="100%">

<mx:DataGrid width="100%" height="66%">
</mx:DataGrid>

<mx:TextArea width="100%" height="34%" />

</mx:VDividedBox>
</mx:Application>

Now, let’s add the columns for the data grid. As a child of the DataGrid, add two DataGridColumn elements to the columns array. Then change the headerText of the first column to Date and set the dataField to pubDate. pubDate is the name of the property of the items in the data grid that will be displayed in that column. Date will be what is displayed in the column header. For the second column, change the headerText to Title and the dataField to title.


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
<mx:VDividedBox width="100%" height="100%">

<mx:DataGrid width="100%" height="66%" >
<mx:columns>
<mx:DataGridColumn headerText="Date" dataField="pubDate"/>
<mx:DataGridColumn headerText="Title" dataField="title"/>
</mx:columns>
</mx:DataGrid>

<mx:TextArea width="100%" height="34%" />

</mx:VDividedBox>
</mx:Application>

If you run the application, you’ll see all visual components are visible, as shown in Figure 13-10.

image

Figure 13-10. RSS Reader visual components

Next, let’s load some data. As a child of the <mx:Application> tag, insert an <mx:HTTPService> tag. Notice how the MXML editor automatically gives you suggestions after you start typing, as shown in Figure 13-11.

image

Figure 13-11. Flash Builder 4.7’s MXML editor suggests tags after you begin typing

You can use the keyboard to navigate up and down the list of suggestions, pressing the Enter key when you find the one you need. Add an id attribute with the value feed, and a url attribute with the value http://blobs.adobe.com/labs/feed and then close the element. Save the file.

1. Add an id attribute with value entries to the <mx:DataGrid>. Like defining a variable name, this means you can reference the DataGrid using the name entries.

2. Add a dataProvider attribute with value {feed.lastResult.rss.channel.item} to the <mx:DataGrid>. This will bind the feed retrieved by the HTTPService to the DataGrid.

3. Add an attribute named htmlText to the <mx:TextArea> tag with a value of {entries.selectedItem.description} to bind its contents to the description property of the currently selected item in the entry’s data grid. This means that whenever the selection in the data grid changes, it will automatically update the text in the text area. Sweet automation!

4. The only thing left to do is to add the creationComplete attribute to the <mx:Application> tag with a value of feed.send(). This invokes the send() method of the HTTPService instance you’ve named feed when the application fires itscreationComplete event after all of its children have been created.

5. Save the file, and then click Run image Run RSSReader. Your application should launch in the browser, allowing you to view the contents of the feed.

Summary

Phew! We’ve covered a lot of ground for such a short chapter, so I’ll keep the summary short. You should now have enough of an idea about what Flex is to start exploring more in depth in the next chapter. And you’ve built a semi-useful application to boot.

I’ll see you in the next chapter when you’re hungry for more.