You are on page 1of 279

ADOBE FLEX 3 Developing Rich Client Applications

ADOBE FLEX 3 Developing Rich Client Applications


Introducing Flex 3:......................................................................................................................... 7 Developing Rich Client Applications ............................................................................................... 7 Introducing Mastery Learning .............................................................................................................. 8 Understanding the Course Format ....................................................................................................... 8 Reviewing the Course Prerequisites..................................................................................................... 9 Summary .............................................................................................................................................. 9 Introducing Adobe Flex 3 ............................................................................................................. 10 Understanding rich Internet applications .......................................................................................... 11 Understanding Adobe Flex ................................................................................................................. 12 Understanding Adobe Flex Builder..................................................................................................... 13 Understanding the foundation of the RIA .......................................................................................... 14 Understanding the Flex application process flow .............................................................................. 15 Accessing remote data resources from a Flex application................................................................. 16 Getting help and other resources ...................................................................................................... 16 Summary ............................................................................................................................................ 17 Getting Started with Flex Builder ................................................................................................. 18 Understanding the relationship between Eclipse and Flex Builder ................................................... 19 Exploring the Flex Builder interface ................................................................................................... 20 Creating a project and your first application...................................................................................... 22 Using the main application file ........................................................................................................... 24 Running the application file ............................................................................................................... 24 Compiling the application .................................................................................................................. 24 Grouping projects with workspaces ................................................................................................... 25 Walkthrough 1: Creating a main application file and running it ........................................................ 26 Debugging a Flex application.............................................................................................................. 31 Debugging an application ................................................................................................................... 32 Walkthrough 2: Debugging and using the Debugging Perspective .................................................... 34 Accessing help in Adobe Flex Builder ................................................................................................. 37 Pgina 1 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Learning Flex Fundamentals ........................................................................................................ 39 Creating a simple Flex application...................................................................................................... 40 Walkthrough 1: Creating your first Flex application .......................................................................... 42 Displaying images ............................................................................................................................... 43 Walkthrough 2: Adding images to an application .............................................................................. 45 Laying out a Flex application with containers .................................................................................... 46 Walkthrough 3: Using basic layouts ................................................................................................... 50 Using the Panel container .................................................................................................................. 51 Walkthrough 4: Separating application modules into panels ............................................................ 53 The ControlBar container ................................................................................................................... 54 Walkthrough 5: Using a ControlBar container ................................................................................... 55 Adding user interface controls ........................................................................................................... 56 Creating data bindings between components ................................................................................... 57 Walkthrough 6: Creating data bindings ............................................................................................. 58 Architecting an application with MXML components........................................................................ 59 Walkthrough 7: Creating and instantiating a custom component..................................................... 61 Creating properties and methods for MXML components ................................................................ 62 Walkthrough 8: Creating properties and methods in a component .................................................. 64 Handling Events .......................................................................................................................... 68 Understanding events ........................................................................................................................ 69 Demonstration 1: Viewing system and user events........................................................................... 70 Creating event handlers using inline ActionScript ............................................................................. 70 Walkthrough 1: Using inline ActionScript .......................................................................................... 72 Handling events within ActionScript functions .................................................................................. 73 Walkthrough 2: Using a function for an event handler...................................................................... 74 Placing ActionScript functions in external files .................................................................................. 74 Demonstration 2: Using an external ActionScriptfile ......................................................................... 75 Understanding the Event object ........................................................................................................ 75 Walkthrough 3: Understanding the event object .............................................................................. 79 Demonstration 3: Simplify the event demo ....................................................................................... 80 Using the addEventListener() method ............................................................................................... 80 Walkthrough 4: Using the addEventListener() method ..................................................................... 82 Summary ............................................................................................................................................ 83

Pgina 2 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Review ................................................................................................................................................ 83 Laying out an Application Using Constraint-Based Layout ............................................................. 84 Understanding absolute positioning .................................................................................................. 85 Positioning components within a Canvas container .......................................................................... 85 Walkthrough 1: Positioning components inside a Canvas ................................................................. 87 Creating a constraint-based layout using Flex Builder ....................................................................... 89 Walkthrough 2: Using Design mode to implement a constraint-based layout .................................. 91 Creating a constraint-based layout via MXML ................................................................................... 94 Walkthrough 3: Implementing a constraint-based layout in MXML.................................................. 95 Using Enhanced Constraints............................................................................................................... 95 Demonstration 1: Using Enhanced Constraints ................................................................................. 97 Using constraint-based layouts within nested containers ................................................................. 98 Walkthrough 4: Using custom components in a constraint-based layout ......................................... 99 Summary .......................................................................................................................................... 100 Review .............................................................................................................................................. 100 Lab: 1 ........................................................................................................................................ 101 Part 2: Creating the Contribute page component............................................................................ 104 Part 3: Create the Gallery page component..................................................................................... 107 Using View States for Application Design ................................................................................... 109 Understanding view states ............................................................................................................... 110 Walkthrough 1: Creating two states for the Contact page .............................................................. 113 Controlling view states ..................................................................................................................... 114 Walkthrough 2: Switching states in the Contact form ..................................................................... 115 Reviewing the generated MXML code ............................................................................................. 116 Walkthrough 3: Implementing view states using MXML ................................................................. 119 Creating view states that include custom component states .......................................................... 121 Walkthrough 4: Using custom components with their own view states ......................................... 122 Summary .......................................................................................................................................... 123 Review .............................................................................................................................................. 123 Creating Application Navigation ................................................................................................ 124 Understanding navigator containers and controls........................................................................... 125 Using the LinkBar control ................................................................................................................. 126 Using the TabBar control.................................................................................................................. 126

Pgina 3 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Using the ViewStack container......................................................................................................... 127 Enabling Buttons Dynamically .......................................................................................................... 129 Walkthrough 1: Navigating the Cafe Townsend application using the ViewStack and TabBar control .......................................................................................................................................................... 130 Using the TabNavigator container ................................................................................................... 132 Using the Accordion container ......................................................................................................... 133 Walkthrough 2: Navigating the Cafe Townsend content using the TabNavigator and Accordion containers......................................................................................................................................... 135 Using ButtonBar & ToggleButtonBar................................................................................................ 135 Using the ApplicationControlBar container ..................................................................................... 136 Walkthrough 3: Adding the ApplicationControlBar container to the Cafe Townsend application.. 137 Summary .......................................................................................................................................... 138 Review .............................................................................................................................................. 138 Customizing the Application ...................................................................................................... 139 Customizing Flex application look and feel ...................................................................................... 140 Modifying Styles to change look-and-feel........................................................................................ 141 Using Themes ................................................................................................................................... 146 Walkthrough 1: Changing the look and feel of the Caf Townsend application.............................. 147 Applying behaviors to components.................................................................................................. 149 Walkthrough 2: Add behaviors to the Cafe Townsend seating chart .............................................. 153 Applying transitions to view state changes...................................................................................... 154 Walkthrough 3: Resize the contact Cafe Townsend panel during the view states transition ......... 157 Summary .......................................................................................................................................... 159 Review .............................................................................................................................................. 159 Lab 2: ........................................................................................................................................ 160 Using ActionScript Data Models ................................................................................................. 167 Using the MVC design pattern ......................................................................................................... 168 Creating an MXML data model......................................................................................................... 169 Using ActionScript classes as a data model...................................................................................... 170 Walkthrough 1: Instantiating an Object in MXML from an ActionScript class................................. 175 Creating an ActionScript constructor with parameters ................................................................... 177 Walkthrough 2: Instantiating an Object in ActionScript from an ActionScript class........................ 179 Defining class methods..................................................................................................................... 181 Walkthrough 3: Adding Methods to an ActionScript class............................................................... 183 Pgina 4 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Summary .......................................................................................................................................... 184 Review .............................................................................................................................................. 184 Exchanging Data Between Components Using Custom Events..................................................... 185 Understanding the problem with bindings ...................................................................................... 186 Demonstration 1: Using a binding to get data from a component .................................................. 187 Creating custom events.................................................................................................................... 187 Walkthrough 1 : Creating, dispatching and handling a custom event ............................................. 190 Sending data with a custom event ................................................................................................... 193 Walkthrough 2: Creating a custom event object and dispatching it ................................................ 196 Summary .......................................................................................................................................... 199 Review .............................................................................................................................................. 199 Creating Data Entry Forms ......................................................................................................... 200 Using the Form container................................................................................................................. 201 Walkthrough 1 : Creating a data entry form component ................................................................ 203 Sharing Form Data ............................................................................................................................ 205 Walkthrough 2: Sharing Form Data with the Application ................................................................ 207 Validating form data......................................................................................................................... 209 Triggering validation with events ..................................................................................................... 210 Walkthrough 3: Validating Numeric Input ....................................................................................... 212 Triggering validation with ActionScript ............................................................................................ 213 Walkthrough 4: Triggering Validation with ActionScript.................................................................. 215 Summary .......................................................................................................................................... 216 Review .............................................................................................................................................. 216 Retrieving XML Data with HTTPService ...................................................................................... 217 Retrieving XML data at runtime ....................................................................................................... 218 Handling results................................................................................................................................ 219 Walkthrough 1: Retrieving data at runtime with HTTPService ........................................................ 222 Handling results using an event handler .......................................................................................... 223 Walkthrough 2: Using a result event................................................................................................ 224 Handling faults.................................................................................................................................. 226 Walkthrough 3: Handling a fault event ............................................................................................ 228 Making HTTP requests to different domains ................................................................................... 230 Walkthrough 4: Testing cross-domain policy ................................................................................... 232

Pgina 5 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Making HTTP requests with parameters .......................................................................................... 233 Walkthrough 5: Using HTTPService with parameters ...................................................................... 235 Summary .......................................................................................................................................... 238 Review .............................................................................................................................................. 238 Displaying Data Using the DataGrid ........................................................................................... 239 Using the DataGrid control............................................................................................................... 240 Demonstration 1 : Displaying Simple XML Data in a DataGrid......................................................... 242 Specifying DataGrid columns............................................................................................................ 243 Walkthrough 1: Specifying DataGrid columns ................................................................................. 244 Formatting DataGrid columns .......................................................................................................... 245 Walkthrough 2: Formatting data in DataGrid columns .................................................................... 247 Using item renderers and item editors ............................................................................................ 248 Walkthrough 3: Using a drop-in item editor .................................................................................... 252 Inline item renderers and item editors ............................................................................................ 253 Walkthrough 4: Using an inline item editor ..................................................................................... 254 Item renderer and item editor components .................................................................................... 255 Walkthrough 5: Using a component item renderer ......................................................................... 256 Using the TileList and HorizontalList ................................................................................................ 257 Walkthrough 6: Displaying data with a TileList and HorizontalList .................................................. 257 Using events and selected items with list-based components ........................................................ 259 Walkthrough 7: Using a change event on the TileList ...................................................................... 259 Summary .......................................................................................................................................... 260 Review .............................................................................................................................................. 260 Lab 3 ......................................................................................................................................... 261

Pgina 6 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Introducing Flex 3: Developing Rich Client Applications


In this section of the course, you will learn the course format, prerequisites and topics.

Objectives
After Completing this unit, you should be able to: Describe the target audience and prerequisites for this course Describe the course content and objectives

Topics
In this unit, you will learn about the following topics: Introducing Mastery Learning Understanding the Course Format Reviewing the Course Prerequisites Reviewing the Course Outline

Pgina 7 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Introducing Mastery Learning


Just as there are methodologies for application development, there are methodologies for teaching and learning. The methodology used in this course is mastery learning. Mastery learning includes:
Clearly stated learning objectives Presentation of material to support the learning objectives Model uses of new material Feedback from students Guided practice Each unit in this course starts with the objectives for that unit. The instructor for this course uses slides, the whiteboard and other media to get across concepts. The instructor for this course demonstrates the use of the product. The instructor for this course tests for understanding during and after each unit. Each unit in this course has a series of walkthroughs that you perform along with your instructor so thatyou get familiar with new skills. Each unit in this course concludes with a hands-on lab that lets you practice a set of new skills, on your own, in context. After each lab in this course you review what you have learned and discuss any problems that you may have had while practicing new skills.

Independent practice Closure and testing

Understanding Format

the

Course

This course is divided into 14 units, most of which present new information and contain demonstrations, walkthroughs and a lab. At the end of each unit, you will find a summary and a short review to test your knowledge of the units content. The following icons are used throughout the guide:

Concepts introduce new information.

Demonstrations illustrate new concepts.

Walkthroughs guide you, with the instructors assistance, through procedures.

Labs let you practice new skills on your own.

Summaries provide a brief synopsis of the units content.

Pgina 8 de 274

ADOBE FLEX 3 Developing Rich Client Applications Reviews test how well you remember the concepts from the unit.

Pgina 9 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Reviewing the Course Prerequisites


To gain the most from this class, you should already: Be familiar with an object-oriented programming language such as Java or C++ Be familiar with XML terminology and use

Reviewing the Course Outline


This course is separated into the following 14 modules: Introducing Flex 3: Developing Rich Client Applications Introducing Adobe Flex 3 Getting Started with Flex Builder Learning Flex Fundamentals Handling Events Laying Out an Application Using Constraint-Based Layout Using View States for Application Design Creating Application Navigation Customizing the Application Using ActionScript Data Models Exchanging Data Between Components Using Custom Events Creating Data Entry Forms Retrieving XML Data with HTTPService Displaying Data Using the DataGrid

Summary
The course is presented through a combination of lectures, demonstrations, walkthroughs, and labs To benefit the most from this course you should be familiar with an object oriented programming language and be familiar with XML terminology and use The course consists of 14 modules and 3 lab exercises

Pgina 10 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Introducing Adobe Flex 3


In this unit, you will begin to understand what a rich Internet application (RIA) is, and how Adobe Flex and the Adobe Flash Player help in constructing them. You will also understand the process of how MXML code you write is transformed into a SWF file delivered to the client.

Objectives
After completing this unit, you should be able to: Describe en RIA Explain the different technologies in the Adobe Flex product line Describe what Adobe Flash Player is and some of its features Understand the application flow of a Flex application and how it is transformed into SWF and delivered to the client Know where and how to get help

Topics
In this unit, you will learn about the following topics: Understanding rich Internet applications Understanding Adobe Flex Understanding Adobe Flex Builder Understanding the foundation of the RIA Understanding the Flex application process flow Accessing remote data resources from a Flex application Getting help and other resources

Pgina 11 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Understanding rich Internet applications


A rich Internet application (RIA) combines the best user interface functionality of desktop software applications with the broad reach and low-cost deployment of web applications and the best of interactive, multimedia communications.

The Evolution of applications

Figure 1: Evolution of applications

Aspects of an RIA include


Every user interaction does not require request/web server response Data can be obtained from the server without redrawing entire page Combine the best of desktop, web and communications Efficiently utilize network bandwidth by transmitting only the portion of the data that changed

Advantages of RIAs
Impact of RIAs from businesses that have implemented them 32% far more, or more successful than expected 37% as successful as expected 10% far less, or less than expected 21% have not measured business impact E-commerce sites that use RIAs have more shoppers that convert to buyers and their average order size is larger Manufacturing and travel reservation companies see total ROI benefits from 185% to 1,354%

Note: Information from Forrester research paper located at http://www.adobe.com/resources/business/rich_internet_apps/.

Pgina 12 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Adobes tools for RIA development

Figure 2: Adobes tools for RIAdevelopment

Understanding Adobe Flex


Provides a structured, proven, free, open-source development framework for creating long-term RIA solutions Used to build web sites, intranet and enterprise applications Flex applications run identically in all major browsers leveraging Flash Player and on the desktop using AIR

Figure 3: The major elements of Flex

Pgina 13 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Adobe Flex SDK


Provides skeleton of the application that developers can use to Extend the application using prebuilt components Extend those prebuilt components Build their own components from scratch Rich class library based on ActionScript 3.0 that embodies best practices for building RIAs Contains XML-based language called MXML that provides a declarative way to build applications Contains an ECMAScript compliant scripting language called ActionScript Compiler for creating SWF files from your MXML and ActionScript Example prebuilt components (ActionScript classes) ComboBox DataGrid DateChooser

Understanding Adobe Flex Builder


Adobe Flex Builder accelerates the design, development and testing of rich Internet applications built with Flex

Adobe Flex Builder Standard


Adobe Flex Builder Standard is an Eclipse based development tool enabling Intelligent coding Interactive step-through debugging Visual design interface Imports assets from Adobe Creative Suite 3 making it easy for designers and developers to work together

Adobe Flex Builder Professional


Adobe Flex Builder Professional includes all of the features of the Standard version plus Memory and performance profilers Integrated, automated functional testing support Aimed at building business-critical RIAs Includes data visualization support Create data dashboards using charts Create rich table-based reports with complex grouping and summary features

Pgina 14 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Understanding the foundation of the RIA


Version 9 used with Flex 3 Backbone of the Flash Platform Supports ActionScript 3.0 Object-oriented scripting programming language Compliant with ECMAScript standard - In 2005 Macromedia chaired the ECMAScript committee and Adobe continues to drive evolution of ECMAScript Includes new, optimized ActionScript Virtual Machine (AVM) to execute the ActionScript code Built from the ground up to work with ActionScript 3.0 Significantly faster than earlier versions Full runtime error reporting - In earlier versions many runtime errors would fail in a graceful, but silent fashion Industry standard debugging Stronger compile-time type checking New language elements added E4X (ECMAScript for XML), which adds XML as a native data type Regular expressions Implements event handling based on W3C DOM Events standard Flash Player 9 also contains AVM1 for backwards compatibility with existing and legacy content written in ActionScript 1 and 2

Figure 5: Flash Player Interactivity

Pgina 15 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Understanding the Flex application process flow

Figure 6: Application development process

Client invokes application Flex compiles MXML/ActionScript file into all ActionScript, then creates a SWF SWF is cached If file already requested, cached SWF is delivered Compiled application SWF downloaded to client Application requests additional resources using HTTP, SOAP or AMF

Pgina 16 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Accessing remote data resources from a Flex application


Flex applications can access remote data resources in a number of ways HTTP: Retrieve data via the HTTP/HTTPS protocol Often XML data which is then converted into ActionScript objects SOAP: Retrieve data via web services AMF (Action Message Format): Use this binary protocol to interact with server-side Java objects (POJOs, JavaBeans, EJBs), ColdFusion components, .NET, PHP and Ruby on Rails, all via remoting Adobe products that enable communication from Flex to remote data BlazeDS: Open source product to enable remoting and messaging technologies Remoting enables AMF protocol, and hence communication with Java objects and ColdFusion components Messaging enables real-time data push to Flex clients LiveCycle Data Services: Includes all features of BlazeDS, as well as a data management service Data management service registers client side data models and has LCDS manage changes

Getting help and other resources


Documentation and other resources

Documentation
Flex Resources http://www.adobe.com/go/flex_documentation Flex 3 Help http://livedocs.adobe.com/flex/3/html/index.html Flex ActionScript and MXML Language Reference http://livedocs.adobe.com/flex/3/langref/index.html Documentation ZIP file http://www.adobe.com/go/flex_documentation_zip ActionScript 3 Errors http://livedocs.adobe.com/flex/3/langref/compilerErrors.html

Flex URLs
Flex product page http://www.adobe.com/go/flex Flex Developer Center http://www.adobe.com/devnet/flex/ flex.org: The starting point for developers working with Flex http://flex.org/ Third party Flex sites http://www.cflex.net/

Pgina 17 de 274

ADOBE FLEX 3 Developing Rich Client Applications

BLOGs
Start your blog search at http://flex.org/blogs/, and link to hundreds of Flex blogs from there

Summary
A rich Internet application (RIA) combines the best user interface functionality of desktop software applications with the broad reach and low-cost deployment of web applications and the best of interactive, multimedia communications The Flex SDK provides a skeleton of the application that developers can use to extend the application Flex Builder is an Eclipse based tool for use in creating Flex applications Flash Player released with Flex forms the backbone of the Flash Platform

Pgina 18 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Getting Started with Flex Builder


In this module, you will explore Flex Builder and use it to create Flex application files in both Source and Design mode. You will also learn how to use the integrated debugger.

Objectives
After Completing this unit, you should be able to: Explain how Flex Builder is based on Eclipse Understand Flex Builder Technology like views, perspectives and editors Create Flex project Create, compile and run a Flex application file Add to an application file in both Source mode and Design mode Use breakpoints while debugging an application

Topics
In this unit, you will learn about the following topics: Understanding the relationship between Eclipse and Flex Builder Exploring the Flex Builder interface Creating a project and your first application Debugging a Flex application Accessing help in Adobe Flex Builder

Pgina 19 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Understanding the relationship between Eclipse and Flex Builder


Flex Builder is built on Eclipse Integrated development environment (IDE) for building Flex applications

The Eclipse Foundation


Not for profit organization Open source community whose projects are focused on providing a vendorneutral open development platform and application framework for building software Based on software released by IBM in November 2001 into the public domain Hundreds of plug-ins available for different environments CFEclipse for ColdFusion Java C/C++

Flex Builder
Flex Builder based on the Eclipse workbench

Installation options
Flex Builder is available in two configurations: Stand-alone configuration: Customized package of Eclipse and Flex Builder plug-ins - Ideal for new users of Flex Builder and those who intend to develop only Flex and ActionScript 3 applications - Can add in other plug-ins, like ColdFusion and Java Plug-in configuration: For those who already use Eclipse and want to add the Flex Builder functionality

Flex Builder functionality


Flex Builder has the following functionality: Coding environment with many helpful tools Interface design environment with visual layout Debugging environment with integrated debugger and variable evaluation options Integrated compiler to build SWF bytecode from MXML and ActionScript

Pgina 20 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Exploring the Flex Builder interface


The term workbench refers to the complete Flex Builder development environment Container for all tools you will use to develop applications Contains perspectives, editors and views

Understanding editors
An editor is where files of various types are edited in either Source mode or Design mode Flex development consists mostly of MXML and ActionScript files, but Java, ColdFusion and CSS files may also be used Edit files in either Source mode or Design mode - Source mode is where you see code - Design mode is where you can create your applications visually Double clicking the editor tab maximizes and minimizes the editor Turn on line numbers in an editor by right clicking in the marker bar and selecting Show Line Numbers

Figure 1: Turning on line numbers

Understanding views
A view supplies support tools when modifying a file in an editor Navigator view allows you to manage files, folders and projects Problems view shows errors in your code Outline view hierarchically presents, and allows you to navigate to, all of the user interface and code elements in a file

From the menu system choose Window to get to various views

Pgina 20 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Understanding perspectives
A perspective is a group of views and editors laid out in a configuration of your choice Flex Builder has two default perspectives - Development perspective - Debugging perspective May have other perspectives if using plug-in configuration, like Java Can create and save your own perspectives from the Window menu

Figure 2: The Flex Builder workbench in Source mode

Figure 3: The Flex Builder workbench in Design mode

Pgina 21 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Creating a project and your first application


To begin development, you need to learn how to Create a Flex Builder project Create a main application page Compile the application Run the application

Creating a Project
A project is a grouping of resources that make up a Flex application Must have a project to create an application in Flex Builder Project name must be numbers and letters only Files will be stored automatically in the project location The main application file will be built automatically and saved at the root of the project location folder When a project is created, a number of files and folders are automatically created bin-debug folder: Where your compiled application resides html-template folder: Where the html wrapper page resides .settings folder: Where some project configuration files reside .actionScriptPoperties, .flexProperties and .project files: Project configuration files src folder: Where MXML files and other asset folders reside libs folder: Where custom class files can reside A main application file, if you do not select an existing file for that role Supply the following information to create a project

Figure 4: Choose a project name and location

Pgina 22 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Figure 5: Specifyc output folder. The default is the bin-debug folder

Figure 6: Set project build paths

Pgina 23 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Using the main application file


The main application file contains the <mx:Application> container tag set Each application can only have one associated application file <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> </mx:Application> The layout property is given the value absolute the first time you create an application Flex Builder will retain your last layout selection for future applications Using the absolute layout requires that all visual elements have specific x,y values or constraints for positioning Other layout choices horizontal: Visual elements laid out horizontally vertical: Visual elements laid out vertically If you do not specify the layout property the layout will be vertical

Running the application file


To test the application file, you run it from within Flex Builder Use the Run button or CTRL+F11 Must be an application file, which means it must contain an <mx:Application> container tag set Green triangle on top left of file icon in the Navigator view indicates file is an application If an application file is not marked with a green triangle you can still run it, then it will appear with a green triangle

Figure 7: File list with marked application

Compiling the application


When the application file runs, the MXML code is compiled into a SWF file that the Flash Player will execute Can set to compile after every save by choosing Project > Build Automatically

Pgina 24 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Grouping projects with workspaces


A workspace (not to be confused with workbench) is a grouping of projects Actual file system directory that contains the files and folders that track a group of projects Can only have one workspace open at a time To create a new workspace Select File > Switch Workspace Click Other... Click Browse...

Figure 8: The Workspace Launcher dialog box

Click the Make New Folder button and create the new folder to correspond to the new workspace

Figure 9: Click the Make New Folder button to create a new workspace

To select an existing workspace Select File > Switch Workspace Click Other... From the drop down select the folder that corresponds to the wanted workspace

Figure 10: Selecting an existing workspace

Pgina 25 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 1: Creating a main application file and running it


In this walkthrough, you will perform the following tasks: Create a new Flex Builder project Create a main MXML application file Use Design mode to place two controls on the page Run the file Manipulate views Change perspectives

Steps
Create a project and the application page
1. Navigate to <installDirectory>/addbeTraining/f3rca/fb.zip. 2. Extract the zip to the adobeTraining/f3rca directory. 3. Open Flex Builder. 4. Select Basic configuration if asked. 5. Right click in the Navigator view and select New > Flex Project. 6. Supply the following information: Project name: F B Project location: <installDirectory>/adobeTraining/f3rca/fb Note: You will need to deselect the Use default location checkbox to enter t correct path. 7. Click Next. 8. Specify the folder where your compiled Flex application will be output. Output folder: b i n - d e b u g 9. Click Next. 10. Set the build paths for the new flex project. Main source folder: src Main application file: FB_wtl .mxml 11. Click Finish.
12. Be sure the empty application code appears in the editor as shown here

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

</mx:Application>

Pgina 26 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Turn on editor line numbers


13. Right click in the margin to the left of the MXML code in the editor and turn on line numbers for editors. Note: If the line numbers are already on do not select Show Line Numbers or it will toggle them off.

Turning Build Automatically on


14. From the Project menu be sure Build Automatically has a check mark in front of it:

Figure 11: Build Automatically will compile your file on save

Note: If there is not a check mark, select Build Automatically. If there is already a checkmark, do nothing.

Adding controls in Design mode


15. Just below the editor tab where the filename appears, click the Design tab. 16. Locate the Controls folder in the Components view (docked at the lower left hand side of Flex Builder).

Figure 12: The Controls folder from the Components view

17. Drag a Label control onto the design surface and place it in the upper left portion of the editor. 18. Use the Flex Properties view to set the text property to Enter Your first name:

Pgina 27 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Figure 13: The text property from the MXML Properties View

19. From the Components view drag a Textlnput control to the right of the Label control.

Note: Use the snap to lines to align the Textlnput control properly. 20. Your editor should appear similar to the following:

Figure 14: The layout of two controls

21. Save the file. Note: Because you have Build Automatically turned on, as soon as you saved the file, Flex Builder began the process of compiling your MXML code into a SWF file that the Flash Player can use. Any compilation errors will be indicated in the Problems view. 22. Place the mouse pointer over the Run button. Notice a tool tip pops up and tells you FB_wtl will be run. Click the button to run the application. 23. You should see the Label and Textlnput. Enter text into the Textlnput. 24. Return to Flex Builder, then click the lab to view Source mode. Examine I the MXML code generated.

Changing the size of the editor


25. Double click the editor s tab to maximize the tab. 26. Double click the tab again to restore it to its previous size.

Note: You can also maximize and restore views in this way.

Pgina 28 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Manipulating views
27. Close the Navigator view by clicking on the X on the tab:

Figure 15: Closing a view

28. Reopen the Navigator view by selecting Window > Flex Navigator. Note: If using the Flex Builder plugin, Window > Show View > Navigator. 29. Open the internal web browser view by selecting Window > Other Views... Note: If using the Flex Builder plugin, Window > Web Browser > Internal Web Browser 30. From the Show View dialog box, click on the plus sign in front of the General folder, men select the Internal Web Browser view. Click OK. Note: The Internal Weh Browser cannot be used for running or debugging programs. These functions will always take place in an external browser.

31. Close the Internal Web Browser view.

Switch perspectives
32. Use the Open Perspective button to select the Flex Debugging perspective. 33. Use the chevron () to switch back to the Flex Development perspective. Note: The chevron is really just an indicator there is more to the right. If you drag the displayed perspective tab to the left you will be able to see both perspectives listed, as shown in the following diagram.

Pgina 29 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Figure 16: Displaying both perspectives

Working with workspaces


34. Select File > Switch Workspace > Other... 35. From the Workspace Launcher dialog box click the Browse... button. 36. Select the directory which you want to be the parent of the soon to be created workspace folder. Note: In the standard Windows installation, this folder is suggested to be: C:\Documents and Settings\<username> \My Documents\Flex Builder 3.

37. Click the Make New Folder button and name the new folder testWorkspace. 38. Click OK. 39. Be sure the new directory is selected in the Workspace Launcher dialog box. 40. Click OK. Flex Builder close and then reopen in the new, empty workspace. Note: You will have to reset some preferences in the new workspace, such as visible line numbers. 41. Switch back to the default workspace, File > Switch Workspace, which corresponds to the directory Flex Builder 3. 42. Close any editors that may be open.

Pgina 30 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Debugging a Flex application


When debugging an application you can control the execution of the application at specific points in the code A special debug version of the Flash Player is used which is installed during the Flex Builder installation When debugging you can Use the trace() function to display values in the Console view Set breakpoints to suspend execution of application code so you can inspect code Monitor variable values Step through code execution

Tracing variable values


Use the trace() function Display variables and text Examples

trace("In the function"); trace(myVar); trace("myVar = " + myVar); Must use Flash Debug Player to view console output

Setting breakpoints
To set breakpoints Must be ActionScript code An MXML tag that contains ActionScript In a Script block Invalid line for setting a breakpoint <mx:Label text="Welcome!"/> Valid line for setting a breakpoint since ActionScript is in the tag <mx:Button label="Purchase" click="buy()"/> To set a breakpoint, use the marker bar, which is the left edge of an editor Double-click to add a breakpoint Or in the marker bar, right click and select Toggle Breakpoint

Pgina 31 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Figure 17: Adding a breakpoint

Run > Remove All Breakpoints to clear the breakpoints

Debugging an application
Start by using the Debug button Click down arrow beside the debug button Select application from drop-down list

Figure 18: Debugging an application

When the breakpoint is encountered the Flex Debugging perspective is activated in the workbench Use debug view to control debug session Suspend, resume or terminate debug session Resume, Step Into, Step Over and Step Return buttons

Figure 19: The debug view

Pgina 32 de 274

ADOBE FLEX 3 Developing Rich Client Applications Use the Variables view to see all variables for the application

Figure 20: The variables view

Use Expressions view to see the variables you choose

Figure 21: The expressions view

BE SURE to stop the debugging session before continuing other work Browser opened for the debugging session will automatically close

Pgina 33 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 2: Debugging and using the Debugging Perspective


In this walkthrough, you will perform the following tasks: Use the trace statement Set a breakpoint for debugging Debug an application End a debugging session

Steps
Create a new application
1. 2. 3.

In Flex Builder, open FB_wt2.txt at the root of the FB project in the src directory. Highlight all of the lines of FB_wt2.txt and press Ctrl-C. Create a new mxml application.


4.

File > New > MXML Application Parent Folder: FB/src Filename: FB_wt2.mxml . Click Finish

Highlight all of the lines in the FB_wt2.mxml file and press Ctrl-V to paste in the contents of the FB_wt2.txt file.

Using the trace statement


5. 6. 7. 8.

Notice that there is a trace statement in the <mx:Script> block. Use the Debug button to run the application. Once the application runs, return to Flex Builder. Examine the Console view, which by default will appear in the bottom of the workbench tabbed with the Problems view, and see that the text from the trace statement is displayed. Terminate the debugging session by clicking the red square in the Console view.

9.

Setting a breakpoint and using the Debugging perspective


10. Switch to the Debugging perspective by clicking the Open Perspective or chevron in the upper right

corner of the workbench, and then select Flex Debugging.


11. The views associated with the Debugging perspective should appear 12. In the marker bar, which is situated to the left of the line numbers, insert a breakpoint on the line which

sets the my Var variable to the value of 10.

Pgina 34 de 274

ADOBE FLEX 3 Developing Rich Client Applications Note: You can insert a breakpoint by double clicking in the marker bar next to the line, or right clicking on the line and selecting Toggle Breakpoint.
13. Check to be sure the breakpoint was set by looking for the blue dot next to the correct line:

Figure 22: The breakpoint displayed in the marker bar

14. Click the tab to see the Expressions view. 15. Right click in the view and select Add Watch Expression... 16. In the Add Watch Expression dialog box enter my Var. 17. Click OK.

Note: You can also set Watch Expression variables during the debugging session.
18. Debug the application.

You will see the browser start, then Flex Builder will appear again when program execution hits the breakpoint. Note: You do not have to be in the Debugging perspective when you set breakpoints. If you set breakpoints in the Development perspective, then debug your application, Flex Builder will either change to Debugging mode or prompt you if you wish to be.
19. In the Expressions view, check to see that the myVar variable is undefined. This is because the

breakpoint stops before executing the specified line of code.


20. Click the Step Into button on the top of the Debug view to execute the marked line of code. 21. Check the value of the variable in the Expressions view. You should see it is now reflecting the

assignment statement, and the value is shown as 10.


22. Click the tab to see the Variables view. 23. View the value of myVar. 24. Terminate the debugging session by clicking the red square either at the top of the Debug or the Console

view.
25. Clear the current breakpoint, then add another on the line that contains the <mx: Button> tag. 26. Debug the application again. 27. Click the Button in the application and return to Flex Builder and be sure the Flex Debugging

perspective is open.

Pgina 35 de 274

ADOBE FLEX 3 Developing Rich Client Applications


28. Continue to use the Step Into button to see the function get called and the newVar variable assigned a

value.
29. Stop the debugging session by clicking the red square either at the top of the Debug or the Console

view.
30. Close any open editors. 31. Return to the Development perspective. 32. Select the workspace at <installDirectory>/ adobeTraining/ f3rca.

Pgina 36 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Accessing help in Adobe Flex Builder


Help is available within Flex Builder and through other sources

Help inside Flex Builder


Get context sensitive help by pressing F1 Searchable Flex and Flex Builder documentation using Help > Help Contents Welcome page from Help > Flex Start Page Sample applications Tutorials

Documentation
Flex Resources http://www.adobe.com/go/flex_documentation LiveDocs http://www.adobe.com/go/flex2_livedocs Flex ActionScript and MXML Language Reference http://www.adobe.com/go/flex2_apiref Documentation ZIP file http://www.adobe.com/go/flex_documentation_zip ActionScript 3 Errors http://www.adobe.com/go/AS3errors Flex Getting Started Experience http://learn.adobe.com/wiki/display/Flex/Getting+Started

Summary

Adobe Flex Builder is based on the Eclipse development environment Flex Builder can be installed as a stand-alone product or as a plug-in to an existing Eclipse installation The term workbench refers to the complete Flex Builder development environment An editor is where files of various types are modified A view contains support tools for modifying a file in an editor A perspective is a group of views and editors laid out in a configuration of your choice A project is a group of resources that make up a Flex application An Flex application is contained within an <mx:Application> component tag set Workspaces are used to group projects When debugging you can Add a trace() statement to display data in the console view Set breakpoints to suspend execution of application code to inspect code and variable values as well as walkthrough code execution Locate source code by pressing Ctrl while clicking the tag

Pgina 37 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Review
1. What is the relationship between Adobe Flex Builder and Eclipse? 2. What is an editor? 3. What is a view? 4. What is a perspective? 5. What determines if a file is an application file? 6. What is a workspace and how do you create one? 7. Name the two places a breakpoint can be set.
8.

Name four ways to get help.

Pgina 38 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Learning Flex Fundamentals


In this section of the course, you will develop your first Flex application and understand the basic infrastructure that a Flex application must have.

Objectives
After completing this unit, you should be able to: Create a Flex application (MXML, file) Layout an application with containers Add simple user interface controls Create data bindings between controls Architect an applications using MXML components

Topics
In this unit, you will learn about the following topics: Creating a simple Flex application Displaying images Laying out a Flex application with containers Using the Panel container Using the ControlBar container Adding user interface controls Creating data bindings between components Architecting an application with MXML components Creating properties and methods for MXML components

Pgina 39 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Creating a simple Flex application


Skeleton of an MXML application file contains XML document type declaration Opening and closing <mx:Application> component tag set

<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <!-- body of application here --> </mx:Application> <mx:Application> is the default container tag

Specifying a namespace
Use the xmlns:mx attribute for the namespace, which defines the collection of legal MXML tags http://www.adobe.com/2006/mxml is a Uniform Resource Identifier (URI) which associates a prefix (in this case mx) with a manifest file as follows <namespace> <uri>http://www.adobe.com/2006/mxml</uri> <manifest>mxml-manifest.xml</manifest> </namespace> flex-config.xml located in installdirectory\Adobe\Flex Builder 3\sdks\3.0.0\frameworks\flexconfig.xml

Manifest file
The manifest file, mxml-manifest.xml, has a long list of component XML elements, partially shown here

<?xml version="1.0"?> <componentPackage> <component id="Accordion" class="mx.containers/ Accordion"/> <component id="AnimateProperty" class="mx.effects/AnimateProperty"/> <component id="Application" class="mx.core/ Application"/> <component id="ApplicationControlBar" class="mx.containers/ApplicationControlBar"/> <component id="ArrayCollection" class="mx.collections/ArrayCollection"/>
Located in installdirectory\Adobe\Flex Builder 3\sdks\3.0.0\frameworks\

Pgina 40 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Setting the layout property


The layout property defaults to your last selection when building an application or component from the appropriate dialog box absolute: Visual elements must have specific x,y values or constraints for positioning horizontal: Visual elements presented horizontally vertical: Visual elements presented vertically

If the layout property is not used in the Application tag, the default layout is vertical

Adding UI controls
UI controls are used to display user interface type components in an application Text, text input, buttons, images, combo boxes, etc. Add between the application tag set or another container component

Also referred to as components Example of the Label control to display a single line of text <mx:Label text="Hello Flexers!"/>

Specifying component properties


Component properties can be specified in two ways As attributes of the XML tag <mx:Label text="Hello"/> As nested tags or nodes

<mx:Label> <mx:text>Hello</mx:text> </mx:Label>

Commenting your MXML code


Use XML style comments which are similar to HTML comments

<!-- this is a comment -->

Pgina 41 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 1: Creating your first Flex application


In this walkthrough, you will perform the following tasks: Create a project and main application page Display some text using a Label control Run the file from within Flex Builder

Steps
Import Flex Project
1. Open Flex Builder if not already opened. 2. Select File > Import > Flex Project. 3. Import project from Archive File. Browse to: <installDirectory>/adobeTraining/f3rca/ FundamentalsProject.zip Click Open Click Finish 4. Open Fundamentals_wt1.mxml in the src folder at root of the Fundamentals project.

Displaying text with a Label control


5. Between the <mx:Application> tag set, add an <mx:Label> control with a text property that has the value Flex is awesome! <mx:Label text="Flex is awesome! "/>

Running the application


6. Run the application. You should see the text appear in the browser.

Pgina 42 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Displaying images
Use the Image control to incorporate JPEGs (progressive and non-progressive) GIFs (can be transparent) PNGs (can be transparent) SWFs SVGs (can only embed at compile time)

Methods for displaying images


Two ways to display images Load them dynamically at runtime Embed them in the SWF file Specify image source three ways Via the source property of an Image control; will load image dynamically at runtime Use the Image load() method to add the image dynamically at runtime Embed the image in the SWF at compile time using the @Embed directive; useful for when you need instantaneous loading and offline applications

Loading dynamically at runtime


Specify the image using the source attribute of the <mx:Image> control Image is loaded at runtime <mx:Image source="myimage.jpg"/> Assign an id to the image to reference in ActionScript

<mx:Image source="addis.jpg" id="imageID"/>

Using the load() method


Dynamically switch out the image using the load() method of the Image class Code example <?xml version="1.0"?> <mx:Application backgroundColor="#FFFFFF" xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:Image source="addis.jpg" id="imageID" maintainAspectRatio="false" width="250" height="250"/> <mx:Button label="Change Pic" click="imageID.load(flower.jpg)"/> </mx:Application>

Pgina 43 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Embedding images at compile time


You can embed images at compile time for instantaneous loading To embed, use the @Embed directive when specifying the image source

<mx:Image source="@Embed(../images/blue1.svg)"/ >

Pros of embedding images


Image is available immediately, it is part of the SWF Very useful for creating applications that are able to work offline

Cons of embedding images


Adds to applications SWF size Slows down application initialization process Must recompile application every time image changes Cannot use in data binding calls

Limitations working with Scalable Vector Graphic (SVG) files


You can only embed an SVG file in an application; you cannot load one at runtime SMIL and animation are not supported Masking and filters are not supported Pattern Fill and some advanced Gradients are not supported Interactivity and scripting is not supported SVG text is rendered as nonsearchable and nonselectable SWF shape outlines, meaning it is not rendered as native text in Flash Player

Pgina 44 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 2: Adding images to an application


In this walkthrough, you will perform the following tasks:

Add an image dynamically Use the load( ) method to switch an image Embed an image

Steps
1. Open the Fundamentals_wt2.mxml file from the src folder at the root the Fundamentals project. 2. After the first Label component, add an Image control with a source set to images/dessert_cheesecake.jpg 3. Add id property with a value of image1 to the Image control.
<mx:Image id="imagel" source = "images/dessert_cheesecake.jpg"/>

4. Run the application. You should see an image of a cheesecake. 5. Add click="image1.load('images/ dessert_cookies.jpg')" to the Image control.
<mx:Image id="image1" source="images/dessert_cheesecake.jpg" click="imagel.load('images/dessert_cookies.jpg')"/>

6. Run the application. 7. Click the image. You should see the image switch when you click the image. 8. After the second Label component, add an Image component with source of
@Embed('images/dessert_breadPudding.jpg') <mx:Image source="@Embed('images/ dessert_breadPudding.jpg')"/>

9. Run the application. You should see an image of bread pudding below image of the cheesecake.

Pgina 45 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Laying out a Flex application with containers


Layout an application using container components Rectangular region of Flash Player drawing surface Hierarchical structure contains controls and other containers Default layout methods to control the layout of its children, including sizing and positioning All containers are children of, and therefore inherit from, the UIComponent and Container classes

Viewing various types of containers with the Flex Component Explorer


Access the Flex Component Explorer http://examples.adobe.com/flex3/componentexplorer/explorer.html

Figure 1: The containers portion of the Flex Explorer

How containers work


Containers use a set of layout rules to position components Keeps you from having to worry about positions Allows easy resizing/re-positioning with browser window size Three-pass algorithm used Commitment Pass - Determines the property settings of the application's components Measurement pass - Size of each component calculated from inside to outside Layout pass - Lays out application from outermost container to innermost

Pgina 46 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Restaurant application example


Sample application UI

Figure 2: Sample applications interface

Under the hood layout of the restaurant finder application

Figure 3: container layout of the applications

Pgina 47 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Box Containers
There are two types of Box containers available to layout pages Vertical box (VBox) Horizontal box (HBox)

VBox
The VBox layout display controls vertically, as in the image below

Figure 4: VBox example

The following MXML snippet shows how you would lay out these three controls using the VBox layout

<mx:VBox> <mx:Label /> <mx:Button /> <mx:Label /> </mx:VBox>

HBox
The HBox layout displays controls horizontally, as in the following image

Figure 5: HVBox example

Canvas container
The Canvas container is a basic container component that enables you to specify absolute positions You can use absolute positioning by specifying x and y properties of the components inside the container <mx:Canvas> <mx:Label x="20" y="10"/> <mx:Label x="100" y="10"/> </mx:Canvas>

Pgina 48 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Canvas containers offer better performance, because client processing power does not have to be used in order to determine object placement You must then handle all positions and layout explicitly, and the application will not scale when the browser window is resized

Specifying positions in a Canvas container


You must specify the x and y properties of all child components inside the container; the origin is the top-left corner of the Canvas

Figure 6: Canvas container x and y values

This x/y positioning is only valid for components on the Canvas, not for components inside child containers

Setting a layout in the <mx:Application> tag


When creating an application, the <mx:Application> tag has the layout property which dictates the type of layout the Application container will utilize Possible values for the layout property absolute: Same as using a Canvas container horizontal: Same as using a HBox container vertical: Default, same as using a VBox container

Pgina 49 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 3: Using basic layouts


In this walkthrough, you will perform the following tasks: Use the Application component's layout property to change the layout of three Labels Use x and y values to absolutely position controls Combine different layouts

Steps
1. 2. Open the Fundamentals_wt 3.mxml file from the src folder at the root of the project. Run the application. You should see that the three Labels are all displaying on top of each other.

Note: Since you are in absolute layout and no x,y positions are specified, all the controls default to position 0,0.

Setting absolute positions on the controls


3. Set the x and y properties as follows. Label 1: x="20" y="25" Label2: x ="0" y="300" Label3: x="300" y="200" Run the application. You should see the Labels are now absolutely positioned.

4.

Using a horizontal layout


Select the value absolulte of the layout property of the Application tag, and then delete it. In the quotes for the layout property, press Ctrl-Space to display code hinting. You will see the possible values for the property. 7. Select horizontal from the code hinting. 8. Run the application. You should see the Labels displayed horizontally. 9. Remove the x and y values on all the Labels. 10. Run the application. You should see the Labels displayed horizontally exactly as they did before. 5. 6.

Using a vertical layout


11. Change the value for the layout property to vertical. 12. Run the application. You should see the Labels displayed vertically.

Combining layouts
13. Surround the last two Labels with a <mx:HBox> container tag set. 14. Run the application. You should see the first Label on one line, then the last two Labels displayed side by side. The vertical container had two children, the first Label and the HBox, so they were displayed vertically. The HBox contains the second and third Labels as children, so they are displayed horizontally.

Pgina 50 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Using the Panel container


The Panel container wraps self-contained application modules

Figure 7: Separate, self contained content in panel container

includes a panel title, a title bar, a status message and a content area for its children

Figure 8: The parts of a Panels Container

is represented in MXML with the Panel tag

Using the Panel tag


<mx:Panel title="Panel Title" status="Panel Status"> ... </mx:Panel> Characteristics default width and height properties set to values that accommodate all children, but will not be larger than allowed by its parent container truncates content that is too large and implements scroll bars as appropriate has a layout property which can take the values absolute, vertical (default) and horizontal has default padding values of 0 pixels

Pgina 51 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Sizing container content


The size of any content placed within a container is relative to that container, not the main Application area

Figure 9: Child content within a container is sized relative to that container

If child content is sized larger than the parent container, then it will be resized down to fit into the parent container

Figure 10: Child content will be resized to fit into the container

Pgina 52 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 4: Separating application modules into panels


In this walkthrough, you will perform the following tasks: Add Panel containers around Text controls Manipulate the Panel container padding values

Steps
1. 2. Open the Fundamentals_wt4.mxml file from the src folder of the root project. Run the application. You should see four text controls laid out horizontally within the Application container.

Add Panel containers and space them evenly


3. 4. 5. 6. 7. 8. Add a Panel tag around the first text control and type How to Find Us for the panels title property. Add a Panel tag around the second and third text controls and type About Cafe Townsend for the panel's title property. Add 4-pixel padding to all sides of this panel using the paddingBottom, paddingLeft, paddingRight and paddingTop style properties. Add a Panel tag around the last text control and type Take a Closer Look for the panel's title property. Add 10-pixel pa ding to all sides of this panel using the paddingBottom, paddingLeft, paddingRight and paddingTop style properties. The code should appear as follows.

<mx:Panel title="How to Find Us"> <mx:Text width="300" text="We are easy to ..." /> </mx:Panel> <mx:Panel title="About Cafe Townsend" paddingBottom="4" paddingLeft="4" paddingRight="4" paddingTop="4"> <mx:Text width="300" text="Cafe Townsends visionary ..." /> <mx:Text width="300" text="The name Cafe Townsend ..." /> </mx:Panel> <mx:Panel title="Take a Closer Look" paddingBottom="10" paddingLeft="10" paddingRight="10" paddingTop="10"> <mx:Text width="300" text="Our private dining room..." /> </mx:Panel>

Pgina 53 de 274

ADOBE FLEX 3 Developing Rich Client Applications 9. Run the application. You should see three horizontally placed panels, each with different padding around their child text controls.

Figure 11: Three panels, each having different padding settings

The ControlBar container


The ControlBar container holds components that can be shared by the other children in the Panel or TitleWindow container

Figure 12: ControlBar container on a panel

must be the last child tag of the Panel or TitleWindow container is a subclass of the Box class, and therefore inherits the layout characteristics of the Box container has a direction property to determine either vertical or horizontal (default) layout of the child components defaults its width and height properties to values that accommodate all children, but will not be larger than allowed by its parent container has default padding values of 10 pixels has horizontalAlign and verticalAlign properties to control the positioning of the child components has verticalGap and horizontalGap properties to set the spacing between children

<mx:ControlBar width="100%"> <mx:Label text="Quantity"/> <mx:NumericStepper id="myNS"/> <mx:Spacer width="100%"/> <mx:Button label="Add to Cart" click="addToCart();"/> </mx:ControlBar>

Pgina 54 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 5: Using a ControlBar container


In this walkthrough, you will perform the following tasks: Add a ControlBar to a Panel container. Add child controls to the ControlBar

Steps
1. 2. Open the Fundamentals_wt5.mxml file from the src folder at the root of the project. Run the application. You should see an image and some text inside a Panel.

Add the ControlBar container


3. 4. 5. 6. 7. 8. 9. As the last element inside of the Panel component, add a ControIBar component. Set the direction property (inherited from Box class) of the ControlBar component to horizontal. Switch to Design mode and drag a Button component from the Controls folder of the Components view and drop it into the ControlBar. Update the Button label property to add to cart. Drag another Button component and drop it to the right of the existing Button component. Update the Button label property to add to wishlist. Run the application. You should see the ControlBar with two buttons at the bottom of the Panel container.

Pgina 55 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Adding user interface controls


Controls are user interface components Button, TextInput, TextArea, ComboBox Controls are placed inside containers

Label control revisited


The Label control is used to display a single line of text There are two ways you can use the <mx:Label> tag to display text Specify the text as a property, as in the following

<mx:Label text="Hello World!"/> Specify the text as a subtag, as in the following

<mx:Label> <mx:text>Hello World!</mx:text> </mx:Label>

TextInput control
The TextInput control is used to gather information from the user in a single line of text You can also optionally Enable borders Use a restrict attribute for simple user input checking - The restrict property can specify a set of allowable characters, as in the following example restrict="0-9a-zA-Z"

Figure 13: The TexInput control

A sample <mx:TextInput> tag is shown in the code below <mx:HBox> <mx:Label text="Name:"/> <mx:TextInput width="175" text="Prefill with text property"/> </mx:HBox>

Pgina 56 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Creating data bindings between components


Data binding is the process of binding the data of one object to another object Two ways to perform a binding Curly braces syntax ( { } ) <mx:Binding> tag

Assigning instance names


Most MXML tags refer to classes When you use the tag, you create an instance of the class Use the id property to assign an instance name Allows you to refer to the object created <mx:Label id="labelOne" text="Hello"/>

Creating data bindings


Using the curly braces syntax Assigns a property a dynamic instead of literal value Uses a broadcast/listener method <mx:Label id="labelOne" text="hello"/> <mx:Label text="{labelOne.text}"/> Using the <mx:Binding> tag Specify the source and destination property values <mx:Label id="labelTwo" text="hello"/> <mx:Label id="labelThree"/> <mx:Binding source="labelTwo.text" destination="labelThree.text"/>

Pgina 57 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 6: Creating data bindings


In this walkthrough, you will perform the following tasks: Bind using the curly brace syntax Bind a static value from one component to another Bind a variable value from one component to another

Steps
1. Open the Fundamentals_wt6.mxml file from the src folder at the root of the project.

Creating a data binding


2. Add a Labelcontrol with an id of myLabel and a text property set equal to This is a Label. <mx:Label id ="myLabel" text="This is a Label"/) 3. Add another Label control with a text property bound to the width property of the label named myLabel. text="{myLabel.width}"/>

<mx:Label 4.

Run the application. You should see the Label containing text, and the width displayed below.

Binding to a dynamic value


5. Addan<mx:TextInput>tagwithan i d of mylnput. <mx:TextInput id = "my Input"/> 6. Belowthe Textlnput, add a Label with a text property bound 1 mylnput. text.

<mx:Label text="{myInput.text}"/> 7. Run the application. As you type in the input field, you should see that binding dynamically alters the text in the other Label.

Pgina 58 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Architecting an application with MXML components


In general, all your application code should not be in one monolithic file A best practice is to break your application into multiple MXML files Breaking up your application into components has the following benefits Allows multiple developers to work on the application Makes it easier to maintain the application The application is more logically structured into smaller pieces Enables parts of the application to be reused elsewhere

Using MXML components


When you separate your application into multiple MXML files Each file is an MXML component The main MXML application manages the individual components Each component often represents a different state of the application There can only be one Application tag in the main MXML doc; everything else is a component

Figure14- And application using Canvas components with a TabNavigator control

Creating MXML components


To create a MXML component Create a new MXML Component file Instead of using an <mx:Application> tag, use any another component tag such as VBox, Form, Button, etc. <?xml version="1.0" encoding="utf-8"?> <mx:Form xmlns:mx="http://www.adobe.com/2006/mxml"> </mx:Form> Avoid using any unnecessary containers for performance reasons In the following component, it would be better just to use the Canvas as the base tag, instead of a Canvas inside a VBox

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

Pgina 59 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Instantiating MXML components


Once the application has been broken into separate components, those components can be instantiated from within the MXML application Add an XML namespace May create any name not already in use Help avoid naming collisions Get code hinting access in Flex Builder Use * to represent all the components in a particular folder For example xmlns[:prefix]="subfoldername.* <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:comp="components.*" > Instantiate components like any other MXML tag - Use correct namespace

<comp:Component1/>

Pgina 60 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 7: Creating and instantiating a custom component


In this walkthrough, you will perform the following tasks: Create a simple custom MXML component that extends a VBox Instantiate the custom component from an MXML main application page

Steps
Create a new component
1. 2. 3. 4. 5. 6. 7. 8. 9. Right-click on the components folder in the Fundamentals project. Select New > MXML Component Be sure Fundamentals/src/components is the parent folder. Enter the Filename to be MyFirstComp. mxml. Select VBox to be the base component. Click Finish. In the VBOX tag, remove the width and height properties. Add a backgroundColor property and set it to yellow. In the component, simply display some text that indicates you are in the component, something like the following. text = "***Start of Component***"/> text = "My First Component"/> text = "***End of Component***"/>

<mx:Label <mx:Label <mx:Label

10. Save the file.

Instantiate the component


11. Open the Fundamentals_wt7.mxml file from the src folder at the root of the Fundamentals project. 12. Add an additional namespace declaration in the Application tag to make available all components in the directory where you just placed your first component. Specify the prefix to be comp. xmlns:comp="components.*" 13. Where indicated by the comment, instantiate your custom component. <comp:MyFirstComp/> 14. Run the application. You should see by the background color and order of the text that the component was called.

Pgina 61 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Creating properties and methods for MXML components


When you create an MXML component, you are actually building a new ActionScript class Flex and MXML hide much of the complexity of this process As with any OO (Object Oriented) class, you must know how to create properties and class methods

Creating properties within MXML components


Use a <mx:Script> block Can be placed anywhere inside root tag; usually placed at top Write ActionScript 3.0 code inside Specify the access modifier for the variable public, private, protected or internal Use the var keyword to declare the property Use post colon syntax data typing to type the property Use CDATA section to escape all characters inside, so the code is not parsed by the XML parser

<mx:Script> <![CDATA[ public var internalProp:String; ]]> </mx:Script>

Referencing MXML component properties


When instantiating the component via MXML, assign a value to its id property so the instance can later be referenced via ActionScript Then use the components property as you would any other object property <comp:Component1 id="myC"/> <mx:Label text="{myC.internalProp}"/>

Creating bindable properties


Many properties will be used in binding operations You must specify which properties will be used in bindings Use the [Bindable] metadata tag that instructs the Flex compiler to make this item available for data binding [Bindable] private var prop1:String;

Pgina 62 de 274

ADOBE FLEX 3 Developing Rich Client Applications

If you have a series of bindable variables, you must use the [Bindable] metadata tag for each [Bindable] private var prop1:String; [Bindable] private var prop2:Boolean;

Creating methods for MXML components


Use a <mx:Script> block Create an ActionScript function inside <mx:Script> <![CDATA[ public function test():String { return "From the method"; } ]]> </mx:Script>

Referencing MXML component methods


When the component that contains the method is instantiated, assign an id to give the component an instance name Then use the components method as you would any other public class method <comp:Component1 id="myC"/> <mx:Label text="{myC.test()}"/>

Commenting ActionScript code


Use ActionScript comments // for single line /* for multi-line comments */

Pgina 63 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 8: Creating properties and methods in a component


In this walkthrough, you will perform the following tasks: Create a property in a component Display the property's value in both the component and the instantiating application Create a method that returns a value to the instantiating application

1.

comp refers to the namespace for all of the files in the components directory.

2.

PropMethod references the component.

3.

myComp represents this instance of the PropMethod custom component.

4.

Pass the pro pi property into the custom component.

5.

Retrieve pcopl for display within the custom component.

6.

Display the propl property data from the custom component.

7.

Call the custom component method.

Figure 15: Calling a custom component

Steps
1. Open the PropMethod.mxml file in the components folder within the src folder at the root of the project.

Adding a property to the component


2. 3. After the VBox container, add an <mx:Script> block. In the Script body, using a Var statement, create a property named prop1, with an access modifier of public and data typed as String.

public var prop1:String; 4. Below the Script block, display the value of the property using a Label control and curly brace data binding syntax. text="{prop1} "/>

<mx:Label 5.

Save the file.

Pgina 64 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Instantiating the component and passing a property value


6. Open the Fundamentals_wt8.mxml file from the src folder at the root of the Fundamentals project. 7. Add the following namespace declaration in the Application tag so you can use the component you just altered. Specify the prefix to be comp.

xmlns:comp="components.*"
8. Instantiate the component via MXML and initialize the property just created to your name.

<comp:PropMethod prop1="Your Name"/>


9. Run the application. The application will run correctly, but when you return to Flex Builder you will see the following warning in the Problem view. Data binding will not be able to detect assignments to "prop1". This means that if the value of prop1 changes, the binding will not be updated because you did not use a metadata tag to mark the property bindable.

Indicating a property is available for data binding


10. In the component, just above the variable declaration for prop1, use a metadata tag to mark the property bindable.

[Bindable] public var prop1: String;


11. Run the application. You should see your name appear without any warnings in Flex Builder. 12.In the component, change the access modifier from public to private and save the file. 13.Run the application. You should see a runtime error appear that confirms that properties of components that have data passed to them must be public. 14.Change the access modifier back to public and save the file.

Using a components property value in the instantiating MXML file


15. In the main application page, add an id property with a value of myComp to the installation of the component 16. Below the component instantiation, use a Label control to display the value of prop1 using data binding

<mx:Label text ="{ myComp.prop1} "/> 17. Run the application. You should see your name is now displayed twice.

Pgina 65 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Adding a method within the component


18. Return to PropMethod.mxml. 19. Below the declaration of the property in the Script block, add a function named method1 with an access modifier of public and datatyped as String.

public function methodl():String


{ } 20. In the function, return the string 'Back from the method'.

return "Back from the method";


21. Save the file

Invoking the method of the component from the instantiating MXML file
22. Return to Fundamentals_wt8.mxml. 23. Below the existing Label control, insert another Label control to display the value returned from the method invocation.

<mx:Label text="{myComp.methodl()}"/>
24. Run the application. You should see that in addition to your name being displayed twice, the String value returned from the method is also displayed.

Pgina 66 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Summary
The skeleton of an MXML application file contains an XML document declaration and opening and closing <mx:Application> tag set The namespace declaration defines the collection of available MXML tags Use XML style comments <!-- this is my comment --> Use the Image control to incorporate JPGs, SWFs, PNGs, GIFs and SVGs into your SWF Layout an application using container controls such as VBox, HBox and Canvas The Panel container is commonly used to wrap self-contained application modules The ControlBar container is designed to contain common elements relevant to all children in the Panel or TitleWindow container Controls are user interface components such as Button, TextInput, TextArea, ComboBox, and are placed inside and thus children of containers Data binding is the process of binding the value of a property of one control to a property of another control, using either curly brace syntax ( { } ) or the <mx:Binding> tag It is considered a best practice to break your application into separate and multiple MXML files When you create an MXML component, you are actually building a new ActionScript class

Review
1. What are the two essential elements of a Flex application?

2.

What is the function of the following code in the Application component tag?

xmlns:mx= http://www.adobe.com/2006/mxml

3.

How are the x and y properties interpreted when not inside a Canvas?

4.

What are the two ways to implement data bindings?

5.

What advantages do custom components offer?

6.

How do you create methods within a custom component?

Pgina 67 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Handling Events
In this unit, you will learn about the different kinds of events in Flex and how to handle events.

Objectives
After completing this unit, you should be able to:

Understand the different event types Create event handler code using inline ActionScript Handle events using ActionScript functions Place ActionScript functions in external files Understand the Event Object Create and use an addEventLiStener() method

Topics
In this unit, you will learn about the following topics: Understanding events Creating event handlers using inline ActionScript Handling events within ActionScript functions Placing ActionScript functions in external files Understanding the Event object Using the addEventListener() method

Pgina 68 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Understanding events
Events let the developer know when something happens within a Flex application System initiated Occur as result of systematic code execution e.g., creationComplete, initialize, show Events User initiated Occur as a result of user interaction with a control or container in the application e.g., click, change, mouseOver Events

System events
Occur during normal ActionScript execution either from within the Flex framework or custom code The following occur for every object that is a subclass of UIObject, the parent of all user interface objects in Flex Description Broadcast when an object has finished its construction, property processing, measuring, layout and drawing Set default startup settings on this event, you know all objects are created and ready to use Commonly used with the Application object Broadcasts when the component has finished its construction and has all initialization properties set The initialize event can occur too soon to interact properly with child objects Care must be taken not to execute statements on undefined objects with the initialize event Broadcast when an objects state changes from invisible to visible

Event creationComplete

initialize

show

creationComplete vs. Initialize


For processing you wish to occur at application startup, you will use the creationComplete event For example, data retrieval to populate UI controls

User events
Supports subset of Document Object Model (DOM) Level 3 Events Specification http://www.w3.org/TR/DOM-Level-3-Events/ Event Click change Description A pointing device button is clicked over an element An event that occurs when the value of the control changes, such as each key typed into a TextInput control or a new selection made in a ComboBox control A pointing device button is pressed while the cursor is over a control

mouseDown

Pgina 69 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Demonstration 1: Viewing system and user events


In this demonstration, your instructor will perform the following tasks: Display system events Display user events

Steps
At this point just view what the application does and don't look at the code. Later in the module the code will be examined.

Import Flex Project


1. Select File > Import > Flex Project. 2. Import project from Archive file. Browse to: <installDirectory>/adobeTraining/f3rca/ EventsProject .zip Click Open Click Finish 3. Close all unrelated projects. 4. Open events_demo1.mxml in the src folder at root of the Events project 5. Run the application. Notice the system events that occur for the Test without user interaction. 6. Interact with the Test button to see user events

Creating event handlers using inline ActionScript


Event handlers, also called event listeners, are code you write to respond to events Up to now, the values of attributes and properties have been scalar values, except for bindings

<mx:Button label=Clic k Me/>


When using an event, the value associated with it is ActionScript, which is called an event handler

<mx:TagName eventName=ActionScript code/>


Two ways to implement an event handler Using inline ActionScript Using ActionScript functions in a Script block

Pgina 70 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Creating event handlers using inline ActionScript


Write ActionScript inside a tag

<mx:TagName eventName="[ActionScript statement or function call here]" />


Example: Responding to a Button click event

<mx:Button label="Click Me" click="myLabel.text='You clicked'"/> <mx:Label id="myLabel"/>

Using ActionScript in MXML tags


ActionScript can only be used as a value for an event, not properties Bindings ({}) permit you to use ActionScript as property values

<mx:Button id="myButton" label="Click Me" click="myLabel.text='You clicked'"/> <mx:Label id="myLabel" text="Click {myButton.label}"/>

Pgina 71 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 1: Using inline ActionScript


In this walkthrough, you will perform the following tasks: Add Label and Button controls to an application Handle the click event of a Button

Steps
Import Events Project
1. If not already imported, import the Events project. File > Import > Flex Project Import project from Archive File Browse to: <installDirectory>/adobeTraining/f3rca/ EventsProject.zip Click Open Click Finish 2. 3. Close unrelated projects. Open the events_wtl.mxml file from the src folder in the root of the project.

Adding a Label and Button to the application


4. In the Application container, insert an <mx:Label> control with an id property of myL.

<mx:Label id="myL"/>
5. After the Label control, insert an <mx: Button > control with an id of myButton and a label of Click Me.

Handling the click event of the Button


6. 7. Add ad click event to the Button. Use inline ActionScript to place the text Button Clicked in the Label control.

click="myL.text='Button Clicked'"
8. Run the application. When you click the Button, Flex dispatches the click event, the handler code is executed and the text appears in the Label control.

Pgina 72 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Handling events within ActionScript functions


If you need more than one line of code to handle an event, place the code within a function Enables reuse Keeps code cleaner Place code within a <mx:Script> tag body Everything inside the Script tag body is treated as XML by parser Wrap code in CDATA to prevent the compiler from interpreting the ActionScript code as XML

Defining a function in an MXML document


<mx:Script> <![CDATA[ private function clickHandler():void { myLabel.text="You Clicked"; } ]]> </mx:Script> <mx:Button label="Click Me" click="clickHandler()"/> <mx:Label id="myLabel" />

Pgina 73 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 2: Using a function for an event handler


In this walkthrough, you will perform the following tasks: Create a function Register the function as an event handler

Steps
1. Open the events_wt2.mxml file from the src folder at the root of the project.

Creating a function
2. 3. Below the Application container, insert a script block. Within the Script body, create a private function named clickHandler, datatyped as void.

private function clickHandler():void { }


4. Move the code from the Buttons click event into the function. Add a semicolon to the end of the line of code.

private function clickHandler():void { myL.text="Button Clicked"; }


Note: You can change the single quotes to double quotes, but it is not mandatory.

Calling the function


5. Register the clickHandler() function to be notified when the click event is dispatched.

click="clickHandler()"
6. Run the application. When you click the Button the text appears in the Label, just as it did before moving the code into a function.

Placing ActionScript functions in external files


Functions can be placed in an external ActionScript file Convention is to use .as for the file extension You can use any file extension you want File can only contain functions, variable declarations and comments Do NOT need the CDATA tag set Include the external ActionScript file - Use the source property of the <mx:Script> tag

<mx:Script source="asHandlers.as"/>

Pgina 74 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Demonstration 2: Using an external ActionScriptfile


In this demonstration, your instructor will perform the following tasks: Use a local ActionScript function Use an external ActionScript function

Steps
1. 2. 3. 4. 5. 6. 7. Open the events_demo2.mxml file from the src folder at the root of the project. Examine the code and notice the first Script block. It has an ActionScript function named showLocalFunction that is called t the first Label control. Open the Functions.as file from the src folder at the root of the project. Examine the code. The ActionScript file contains one function named showExternalFunction, Return to events _demo2.mxml. Examine the second Script tag. The source property points to an external ActionScript function that is called by the second Label control. Run the application. You should see two Labels indicating which ActionScript source was used to generate the display.

Understanding the Event object


Every Event object inherits from the flash.events.Event class Each time an event occurs, an Event object is created Event objects contain a large collection of named properties Some are standard properties of the base Event class, others are specific to the event that occurred Refer to the Event object inside an event handler as an object named event

<mx:Button label="Click Me" id="button1" click="fillLabelControl(event)"/>

Event object properties


All Event objects contain properties Some are the same for all events (type and target) Some are specific to the Event being broadcast Some are custom properties the developer specifies in a custom Event class Event type target target.id Type String Object String Description The type of event for example, KeyboardEvent The component instance that broadcast the event A property of the target object, which is the instance name of the target

Pgina 75 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Datatyping the event object


Use the Event class as the datatype when needed

private function aHandler(event:Event):void


More specific Event types are available which are subclasses of Event MouseEvent DragDropEvent ResultEvent Custom Event classes (discussed later in this course) Benefits of datatyping as strictly as possible Faster runtime performance Compile time type checking Access to event specific properties If stricter datatyping is NOT used, may not have access to properties specific to the specific event All event classes not in the flash.events package need to be imported to be used

currentTarget versus target


There are times when it is more convenient to handle an event not on the actual object (or target) that dispatched the event, but on an object that contains the target - its parent container In Flexs event propagation mechanism, you can choose to handle the event at the target or in a container of the target Referred to as event bubbling Three phases in event bubbling in Flexs event propagation sequence Capturing phase: Ancestors are checked to find which are registered as a listener for the event starting with the application object to the direct ancestor of the target Targeting phase: Flex invokes the targets event listeners Bubbling phase: Ancestors are checked to find which are registered listener for the event starting with the direct ancestor of the target to the application object (this is the reverse of the capturing phase)

Figure 1: Event bubbling phases

Note: By default, no container listens during the capturing phase.

Pgina 76 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Every Event object has a target and a currentTarget property that helps you to keep track of where it currently is in the process of propagation The target property refers to the dispatcher of the event The currentTarget property refers to the current object that is being examined for any listeners for the event

Code example
The following code registers listeners for a click event on three different objects, the Application, VBox and the Button The import statement allows access to a package of classes or to a specific class In this case, we import the Alert class within the mx.controls package

<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/ 2006/mxml" click="c1ickHandler(event,'Appiication')"> <mx:Script> <![CDATA[ import mx.controls.Alert; private function clickHandler(event: Event, dispatchingObject:String): void { Alert.show("target: " + event.target.toString( )+"\n\n"+ "currentTarget:" + event.currentTarget.toString( ) + "At the " + dispatchingObject ); } ]]> </mx:Script> <mx:VBox id="my VBox" click="clickHandler(event,'VBox')"> <mx:Button id="myButton" label="Create CIick Event" click="clickHandler(event,'Button')"/> </mx:VBox> </mx:Application>

Results
The Alert boxes are displayed as follows and in this order Note: eventBubbing() refers to the MXML file

Pgina 77 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Figure 2: Alert boxes displayed from the code sample

Image class special case


Normally at the object dispatching the event, the target and currentTarget are the same Use the currentTarget property to always access the object listening for the event When you click on an Image object that is not embedded The currentTarget will be the Image information The target will be an instance of the Loader class used to actually load the image When you click on an embedded image the target will be the Image information

Pgina 78 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 3: Understanding the event object


In this walkthrough, you will perform the following tasks: Dispatch a click event Assign an event handler Display properties of the Event Examine the complete Event object using debugging mode

Steps
1. Open the events_wt3.mxml file from the src folder at the root of the project.

Passing an event object from the Button to the event handler function
2. 3. In the call to the Buttons click event handler, pass a parameter named event. In the clickHandler function, accept a parameter named event datatyped as MouseEvent.

Examining the complete Event object


4. Insert a breakpoint on the last line of the event handler function.

Note: You can do this by double-clicking in the editors left margin next to I line of code.

5.

Change to the Flex Debugging perspective.

Note: If you do not change to the Debugging perspective Flex Builder will prompt you to do so when debugging the application. 6. 7. 8. Debug, rather than run, the application. Click the Button and return to Flex Builder if you are not automatically returned there. Use the Variables view to examine the lengthy event object. Be sure to locate the type and target. i d.

Figure 3: Event object's property list

Tip: Remember you can double click the Variables view tab to open the view full screen.

Pgina 79 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Examine both the target and CurrentTarget properties and notice that in this situation they are the same object. 10. Terminate the current debugging session. 11. Change back to the Development perspective. 9.

Displaying Event object properties


12. In the function, add code to display the target.id and type in the appropriate Labels:

targetLabel.text=event.target.id; typeLabel.text=event.type;
13. Run the application. When you click the button, you should see the event target's id was myButton and the event type was click.

Demonstration 3: Simplify the event demo


In this demonstration, your instructor will perform the following tasks: Show user and system events Explain the use of the Event object to simplify the code from the e demonstration

Steps
1. 2. 3. 4. Open the events_demo3.mxml file from the src folder at the root of project. Run the file and notice the system events that occur without user interaction. Interact with the button labeled Test to see user events. Examine the code and note how the event object was used.

Using the addEventListener() method


There will be times when you want to, or must, add event listeners via ActionScript Classes exist that you can only instantiate in ActionScript, so the MXML syntax for creating the event listener is not available To take advantage of advanced event handling, such as adding and removing listeners as needed, ActionScript must be used Some would rather code in ActionScript than MXML The addEventListener() method of the EventDispatcher class enables you to register event handler functions for a specific Event Can use method on any object that displays in Flash Player since all objects that can be displayed can trace its class inheritance back to the DisplayObject class, which inherits from the EventDispatcher class

Pgina 80 de 274

ADOBE FLEX 3 Developing Rich Client Applications

The addEventListener method, with required parameters only, is shown here

object.addEventListener(eventType:String, listener:Function):void
eventType: A String representation of the type of Event to listen for listener: Function accepts the Event object and processes the event

Note: Other parameters exist but will not be used in this course. The addEventListener() method will implicitly create the event object for you and pass it to the listener function You must declare the Event object parameter in the signature of the listener function It is good practice to remove event listeners if no longer needed using the removeEventListener() method Simple example.

<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> creationComplete="initApp()"> <mx:Script> <![CDATA[ private function initApp( ):void { myButton.addEventListener("click", clickHandler); } private function clickHandler(event: MouseEvent): void { myL.text="Button Clicked"; } ]]> </mx:Script> <mx:Label id="myL" text="Watch here"/> <mx:Button id="myButton" label="Click Me"/> </mx:Application>
The eventType can be the simple string as shown, click, or can also use event type static constants, e.g. MouseEvent.CLICK Should use constants because the compiler will catch typing mistakes in constants, not in strings

myButton.addEventListener(MouseEvent.CLICK, clickHandler);

Pgina 81 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 4: Using the addEventListener() method


In this walkthrough, you will perform the following tasks: Add a listener for a Button click using theaddEventListener() method Display information about the Button click event

Steps
1. Open the events_wt4.mxml file from the src folder at the root of the project.

Using addEventListener()
2. 3. 4. In the Application container, add a creationComplete event to call a function named initApp. In the Script tag body, add a private function named initApp, datatyped as void and taking no parameters. In the function, add a listener on the myButton object that listens for a click event and calls a function named clickckHandler. Be sure to use the appropriate event type static constant.

myButton.addEventListener(MouseEvent.CLICK, clickckHandler);

Removing the normal event handler code


5. 6. Locate the Button near the bottom of the file. Remove the click event and associated code.

Testing the application


7. Run the application. You should see the Labels are filled, and the function specified in the addEventListener() method handles the click event on the Button correctly.

Pgina 82 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Summary
There are two types of events: system and user System events occur through the execution of code - Use the creationComplete event for processing you wish to occur at application start User events occur in response to user actions - Supports subset of DOM Level 3 events Event handlers, also called event listeners, are code you write to respond when events are dispatched There are three ways to specify an event handler Using inline ActionScript Using ActionScript functions in a Script block Using ActionScript functions in an external ActionScript only file If you need more than one line of code to handle an event, place the code in a function within the body of a <mx:Script> tag Every event object is an instance of the flash.events.Events class Functions can be placed in an external ActionScript file and included using the source property of the <mx:Script> tag Each time an event occurs, Flex creates an event object Event objects contain a large collection of named properties Properties vary according to event type All event objects contain the properties type and target because they are inherited from the Event base class You use the addEventListener() method to register a handler function for a specific event in ActionScript The signature of the method is

object.addEventListener(eventType:String, listener:Function):void

Review
1. Name the two general groupings of events.

2.

In what situations would you use the creationComplete event on the Application?

3.

What are the three different ways to create event handlers?

4.

What are the advantages of placing event handlers in a function?

5.

What two properties are always in every event object?

6. Why should you use the strictest class possible when datatyping a parameter passed to an event handler function?

Pgina 83 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Laying out an Application Using Constraint-Based Layout


In this section of the course, you use the constraint-based layout system in conjunction with absolute positioning.

Objectives
After completing this unit, you should be able to: Absolutely position controls and containers in Application, Panel and Canvas containers Create constraint-based layouts using Flex Builders Design mode Create constraint-based layouts by typing MXML Nest constraint-based layouts

Topics
In this unit, you will learn about the following topics: Understanding absolute positioning Positioning components within a Canvas container Creating a constraint-based layout using Flex Builder Creating a constraint-based layout via MXML Using Enhanced Constraints Using constraint-based layouts within nested containers

Pgina 84 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Understanding absolute positioning


The Flex Framework provides two mechanisms for positioning and laying out controls Automatic layout Flex automatically positions a container's children according to each containers default layout rules Absolute positioning You specify each child's x and y property values and any additional constraint-based layout properties

Container support for absolute positioning


Three containers support absolute positioning Application requires setting the layout property to absolute, by default layout is

vertical Panel requires setting the layout property to absolute, by default layout is vertical Canvas always uses absolute positioning (it has no layout property)

Absolute positioning characteristics


The child controls position is specified relative to its parent container using its x and y properties otherwise Flex places the child at position 0, 0 of the parent container When you use absolute positioning, you have full control over the locations of the container's children (this allows you to overlap components) You can control which child is on top of another by ordering the associated MXML code - The code listed last in the editor will appear on top You should be careful when combining percentage sizing with absolute positioning Remember that if a container resizes, the percentage-based components also resize, and the result may include unwanted overlapping of controls

Positioning components within a Canvas container


The Canvas container is a layout container positions children based on their specified X and y property values, where the top left corner of the Canvas container is the origin, or 0,0 point is represented in MXML with the Canvas component has default padding (area between the outside bounds of the control and its content) values of 0 pixels

Figure 1: The Canvas container's origin point is the upper left corner

Pgina 85 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Components within child containers of the Canvas container will use the sizing and layout rules of their immediate parent, not the Canvas container Note: The values for the x andy coordinates can be a positive or negative Number datatype. You can use negative values to place a child outside the visible area of the container, and then useActionScript to move the child to the visible area, possibly in response to an event

Pros and containers

cons

of

Canvas

Pro: Better performance because you do not use client processing power to determine object placement when the container resizes Con: You have to specify all positions and layout

Pgina 86 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 1: Positioning components inside a Canvas


In this walkthrough, you will perform the following tasks: Position text over a seating chart in a Canvas container using absolute positioning

Steps
Import the Constraints Project
1. 2. Select File > Import > Flex Project. Import project from Archive file. Browse to: <installDirectory>/adobeTraining/f3rca/ ConstraintLayoutProject.zip Click Open Click Finish Close all unrelated projects. Open the ConstraintLayout_wt1.mxml file from the src folder at the root of the project.

3. 4.

Create the Canvas container and display the seating chart


5. 6. 7. Switch to Design mode. Drag a Canvas container from the Layout folder of the Components view to the design surface. In the Layout properties of the Flex Properties view, set the Width and height of the Canvas container to 400 pixels and 450 pixels, respectively. 8. Drag an Image control from Controls folder of the Components view into the Canvas container on the design surface. 9. Position it at an X and y position of 20 pixels. 10. In the Common properties of the Flex Properties view, use the Source property to insert the seating_chart. gif file from the assets folder located in the src folder at the root of the project. 11. Run the application. You should see the seating chart.

Position text over the seating chart


12. Drag a Text control from the Controls folder of the Components view to the seating chart and position as shown in the figure.

Figure 2: A Text control positioned over the seating chart

13. Update the text to read Tables can be arranged to accommodate a dance floor.

Pgina 87 de 274

ADOBE FLEX 3 Developing Rich Client Applications 14. Set the Text controls Width to 100 pixels and height to 65. 15. Change the text color to a brick color {#DD7142) using the Style properties of the Flex Properties view.

Figure 3: Changing the Text control color

16. Run the application. You should see the seating chart with the text overlay.

Figure 4: The modified Text control

17. Switch to Source mode and review the code with your instructor.

Pgina 88 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Creating a constraint-based layout using Flex Builder


Constraint-based layout basics Use any of the containers that allow absolute layouts to create constraint-based layouts - Application container - Canvas container - Panel container Ensures that the components adjust intelligently when a user resizes the application window - The adjustments are based on the anchor settings of the child element relative to the edges of the container

Figure 5: if a component is set to a percentage width, it will resize to ensure that the anchor rules stay true

Constraint-based vs. traditional container layout


Pros for constraint-based layout They are good for layouts that need pixel-perfect positioning They make it easy to get basic resizing behavior without having to manage a lot of nested containers Pros for traditional (non constraint-based) layout containers Use them when you have dynamically sized items that push each other out of the way Use them with layouts that only need percentage-width columns Sometimes either technique will accomplish the goal You can mix the two layout techniques

Visually assigning anchors


Constraint-based layouts can be built through writing MXML, however, since the effects are visual, it is often preferable to use Flex Builder's Design mode Steps for setting constraints using Flex Builder's Design mode Select the component to constrain In the Layout properties of the Flex Properties view, select the anchor Enter the number of pixels from the container edge to the child component to be placed

Pgina 89 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Figure 6: The easiest way to create a constraint-based layout is to set the constraint anchors using Flex Builder's Design mode

Note: You may find that in some instances, you get overlapping components with constraint-based layouts. If this is not the behavior you want, add additional anchors to the overlapping elements or set a minimum width and height for the container.

Use care with component width and height properties when using constraint-based layout If you do not specifically define the width and height of some components, like the Text control, you will find that they may be truncated - Setting the width or height to 100% may solve some of the issues If you constrain the left and right sides of a component, Flex Builder will remove the width property If you constrain the top and bottom edges of a component, Flex Builder will remove the height property

Pgina 90 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 2: Using Design mode to implement a constraint-based layout


In this walkthrough, you will perform the following tasks: Create a constraint-based layout for the Cafe Store product display

Steps
1. 2. Open the ConstraintLayout_wt2.mxml file from the src folder at the root of the project. Run the application. You should see details regarding Chef Ipsums newly released DVD. This item is the second item in the Cafe Store so both next and previous button controls are displayed. Resize the browser and note that the positions of the components on screen do not change.

Anchor the Label control horizontally


3. In Flex Builders Design mode, select the Label control that starts with The Cafe Store Presents ;.Check the top middle checkbox of the Anchors option in the Layout section of the Flex Properties view. The Label control will be anchored to both sides of the container which centers the component within the container.

Figure 7: Constraint anchors

Note: The pixel number that is associated with the constraint may be different on your computer. It is dependent on the size of your Design mode display. 4. Run the application. You should see, as you resize the browser, that the Label control always stays centered horizontally in the browser. However, it does sometimes overlap the prev and next buttons.

Anchor the buttons


5. Select the prev button. Anchor the top left and check that the left offset is 25 pixels. This will constrain the button to the left of its container.

Figure 8: Anchor the prev button

Pgina 91 de 274

ADOBE FLEX 3 Developing Rich Client Applications 6. Select the next button. Anchor the top right and set the right offset to 25 pixels. This will constrain the button to the right of its container.

Figure 9: Anchor the next buttom

7.

Run the application. You should see, as you resize the browser, that the prev and next buttons stay in the top left and right corners of the browser, respectively. However, if the browser is resized small enough, you will still get overlapping controls.

Figure 10: Overlapping Label and Button controls

Set a minimum width for the Application


8. In Source mode, add the minWith property to the AppliCation container and set its value to 550 pixels. 9. Run the application. You should see that the application cannot be resized smaller than 550 pixels. This means that you will not get the overlapping problem. If the browser is resized below 550 pixels wide, the application will stop resizing.

Anchor the Image and Text controls


10. In Design mode, select the video image and set the top middle anchor to ensure it stays centered in the browser. 11. Sekct the Text control (with the description of the DVD) and anchor both the left and right top. Set the left and right offsets to 162 and 175 pixels respectively. You should see that the Text control is truncated with only one line of text showing. The Width property has been removed by Flex Builder because the width will now be determined by the containers size.

Figure 11: Set the Text control's horizontal anchors

Pgina 92 de 274

ADOBE FLEX 3 Developing Rich Client Applications

12. Make sure the Text control is still selected and set the top anchor.

Figure 12: Set the Text control top anchor

13. Run the application. You should see that the Text control still only shows one line of text. 14. Make sure the Text control is still selected. Set the bottom anchor. All four anchors should be set now. Note: Design mode does not refresh the display to show the entire paragraph of text

Figure 13: Set the Text control bottom anchor 15. Run the application. 16. You should see that the Text control shows the entire paragraph of text. You will note that this paragraph resizes appropriately according to the dimensions of the application. However, since it is constrained to the bottom of the browser window by a certain pixel value, if you resize the browser from the bottom, you may see that the text disappears even though the browser still has plenty of room. 17. In Design mode, remove the top and bottom anchors. 18. Set the height value to 100%. 19. Run the application. You should see that the Text control is no longer constrained to the bottom and therefore text does not disappear when there is plenty of browser space at the bottom. However, if you do size the browser window from the bottom to truncate the Text control, you do not get a scrollbar. 20. In Design mode, set the height value to 100 pixels. 21. Run the application. You should see that the resizing the browser window to truncate the Text control from the bottom does result in a scrollbar appearing. However, if you do resize from the sides, it can still result in truncated text.

Pgina 93 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Creating a constraint-based layout via MXML


Implement a constraint-based layout in MXML by Defining a custom component inside an absolute layout container Adding one or more anchor styles to the component tag that you would like to anchor Use the top, bottom, left and right styles to specify the distances between the side of the container and component

<mx:Form id="myForm" left="20" right="20"/>

Using horizontalCenter and verticalCenter


Use the horizontalCenter and verticalCenter styles to specify the distance between the components center point and the containers center in the specified direction A horizontalCenter having a positive number moves the component right from the center A horizontalCenter having a negative number moves the component left from the center A verticalCenter having a positive number moves the component down from the center A verticalCenter having a negative number moves the component up from the center

<mx:Panel width="250" height="200" layout="absolute" horizontalCenter="0" verticalCenter="21"> [...] </mx:Panel>

Pgina 94 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 3: Implementing a constraint-based layout in MXML


In this walkthrough, you will perform the following tasks: Recreate the constraint-based layout from the last walkthrough Type MXML code instead of using Flex Builders Design mode to create the layout

Steps
1. 2. Open the ConstraintLayout_wt3.mxml file from the src folder at the root of the project. Run the application. You should see details regarding Chef Ipsums newly I released DVD. This application is similar to the previous walkthrough and will have similar results.

Anchor the Label and Button controls


In Flex Builder s Source mode; locate the < prevButton control. Add the left anchor style and set its value to 23. 4. Locate the The Cafe Store Presents.. . Label control. Add the horizontal Center anchor style and set its value to -2 (negative two). 5. Locate the next > Button control. Add the right anchor style set its value to 25. 6. Run the application. You should see that as you resize the browser, that the prev and next buttons stay in the top left and right corners of the browser, respectively. They also will not overlap the Label control since I the minWidth property has been specified on the Application container MXML tag. 7. Locate the Image control. Add the horizontal Center anchor style and set its value to -6 (negative six). 8. Locate the Text control. Add the left and right anchor styles and set their values to 162 and 187, respectively. 9. Run the application. You should see the Button controls in the left and right corners and the rest of the content centered in the application. The Text control will grow or shrink based on the browser size. However, it will never shrink lower than 650 pixels in width. 10. Remove the width property from the Text control. 11. On the Text control, set the minWidth to 250 and the minHeight to 200. 12. Run the application. You should see that the Text control resizes and shows the scrollbar as appropriate unless you set the browser width smaller than the minWidth. 3.

Using Enhanced Constraints


Enhanced constraints allow sibling objects to be constrained to each other rather than to the parent container Enhanced constraints also must use containers (Application, Module, Canvas, or Panel) Enhanced constraints divide a containers space into rows and columns that is then used to position other components which are constrained by the row and column boundaries Define vertical constraint regions using constraintColumns Contain arrays of ConstraintColumn objects Objects are laid out left to right in order they are defined Define horizontal constraint regions using constraintRow Contain arrays of ConstraintRow objects Objects are laid out top to bottom in the order they are defined Column and row regions have three sizing options: fixed, percent and content. Fixed size - Space allocated is a fixed pixel size Content size - Space allocated is dictated by the size of the child objects in the regions

Pgina 95 de 274

ADOBE FLEX 3 Developing Rich Client Applications Percent size - Space allocated is calculated as a percentage of space remaining after fixed and content sized child objects have been deducted Constraint rows and columns do not have to occupy all of the area in a container Note: A best practice is to ensure the sum of all percent constraints is less than or equal to 100%.

<mx:Canvas> <mx:constraintColumns> <mx:ConstraintColumn id="col1" width="212"/> <mx:ConstraintColumn id="col2" width="100%"/> </mx:constraintColumns> <mx:constraintRows> <mx:ConstraintRow id="row1" height="80%"/> <mx:ConstraintRow id="row2" height="20%"/> </mx:constraintRows> ... </mx:Canvas>

Using ConstraintRow and ConstraintColumn


A child component is anchored to a row or column by appending the regions id to any of the child s constraint parameters (left, right, top, and bottom)

<mx:Panel left="col1:0" right="col1:10"/> <mx:Panel left="col2:10"/> <mx:Panel top="row1:50"/>

The component is constrained relative to the parent container if constraint parameters are not qualified by the constraint region identifier (ConstraintRow ID or ConstraintColumn ID) Components can occupy a single region or span multiple regions

Note: You may use any combination of qualified and unqualified constraint properties but this may cause some constraint properties to be overridden.

Pgina 96 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Demonstration 1: Using Enhanced Constraints


In this demonstration, your instructor will perform the following tasks: Constrain controls to columns and rows Interact with controls

Steps
1. 2. Open the ConstraintLayout_demo.mxml from the src folder at the n of the project Examine the code with your instructor.

There are two constraint columns using percentage space allocation. There are three constraint rows using fixed space allocation. There are three controls that will be constrained by the columns and rows within a Canvas container.

Constrain Button control


3. 4. 5. Locate the Button control. Add the top property set to row3:20. Add the right property set to col1:0. Run the application and notice the placement of the Button control.

Constrain Image control over two rows


6. 7. 8. 9. Locate the Image control. Add the top property set to row1:10. Add the bottom property set to

row2:0.
Run the application and notice the location of the image. Add the left property set to co12:10 and the right property set the col2:10 to the Image control. Run the application and notice the placement of the Image control.

Constrain Label control


10. Locate the title Label control. Add a top property set to row1:20. Add a right property set to col1:10. 11. Run the application.

Interact with controls


12. Click the submit button. You should see the button get larger but remain in its allotted space and right position in the first constraint column. 13. Resize the browser window very small. You should see the Label control remain 10 pixels away from the Image control and you should also see the linage shrink to remain in its constraint column and rows.

Constrain Button control to two columns


14. Return the browser to its normal size. 15. Locate the Button control. Change the value of the right property to coll:10. Add the left property set to coll:10.

Pgina 97 de 274

ADOBE FLEX 3 Developing Rich Client Applications 16. Run the application. You should see the Button control is constrained to its allotted space over two columns. 17. Resize the browser window. You should see the Button control remain 10 pixels from its right and left constraint.

Using constraint-based layouts within nested containers


Constraints in nested containers will be based on their immediate parent container Constraints in custom components will be based on the component container

Figure 14: Constraints are based on their immediate parent container

Pgina 98 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 4: Using custom components in a constraint-based layout


In this walkthrough, you will perform the following tasks: Integrate a custom component which uses constraint-based layout into the Cafe Townsend application.

Steps
1. 2. Open the ConstraintLayout_wt4.mxml file in the src folder at the root of the project. Run the application. You should see the Cafe Townsend application with the three panels on the right. The main content area is a blank white space, but as you increase or decrease the browser size, that area responds to the change.

Add the custom component


3. In Source mode, add an XML namespace declaration named comp to the Application container tag and point it to the current directory. The code should appear as follows.

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:comp="*" layout="vertical" backgroundColor="#000000" backgroundAlpha="0"


themeColor="haloOrange">

4. 5.

Locate the comment on line 42 that prompts you to add the custom component. On line 43, call the CafeStore custom component, which is the CafeStore product display from the previous two walkthroughs. The code should appear as follows.

<mx:VBox paddingRight="8" paddingTop="8" paddingBottom="8" width="100%"> <!-- Add custom component here --> <comp:CafeStore /> </mx:VBox>
6. Run the application. You should see the custom components Cafe Store Products panel appear in the main content area. Resize the browser to see that its constraint-based layout remains bound by the VBox container.

Pgina 99 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Summary
Application, Panel and Canvas containers support absolute positioning The x and y properties used in absolute positioning are ignored if the layout property is not set to absolute
Constraint-based layouts allow developers to adjust the layout intelligently based on the application window dimensions Use the Layout options in the Flex Properties view of Flex Builders Design mode to set the anchors on a component When creating a constraint-based layout in MXML code, simply set a pixel value to one of the six available anchor point styles of a component: top, verticalCenter, bottom, left,

horizontalCenter, right
Constraints in nested containers or custom components will be constrained within the dimensions of their immediate parent Enhanced constraints allow sibling objects to be constrained to each other rather than to the parent container Enhanced constraints divide container space into columns and rows Use ConstraintRow to define horizontal regions and ConstraintColumn to define vertical regions

Review
1. Which style is NOT an anchor property?

right verticalCenter bottom corner 2. In a Panel container whose layout property is set to absolute, where will components be displayed if they do not have either their x or y properties set?

3.

True or false. Percentage sizing cannot be used with absolute positioning?

4.

How can you avoid overlapping components in a constraint-based layout?

5.

Where is the 0,0 point of a container?

6.

What types of layout scenarios benefit from constraint-based layout?

Pgina 100 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Lab: 1
Objectives
In this lab, you will perform the following tasks: Create a Flex Builder project Create a main application MXML file for a Flex application Create custom MXML components and instantiate them Use basic Flex UI controls Use basic Flex container controls

Part 1: Creating the basic photo gallery application & home page
In this part of the lab, you will perform the following tasks: Import Lab1 Project Create the custom component for the homepage Instantiate the custom component on the main application MXML file Use containers and controls to layout and organize the content Include all the components into the main application file

Steps
Import the Lab Project
1. 2. Select File > Import > Flex Project. Import project from Archive File. Browse to: <installDirectory>/adobeTraining/f3rca/ LablProject.zip Click Open Click Finish 3. Close all unrelated projects.

Create the main application file


4. 5. In Adobe Flex Builder, create a new MXML Application by selecting File > New > MXML Application. Supply the following information.FStop Parent Folder: Labl/src File Name: FStop

6.

Click Finish. You should see the new FStop.mxml page appear in the Flex Builder editor within the src folder.

Pgina 101 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Create the main Application MXML file


Make sure you are in Source mode and change the layout property of the Application container tag to vertical instead of absolute. 8. Add the backgroundColor style and set it to black (#000000). 9. Add the backgroundAlpha style and set it to 0. 10. Confirm that the code appears as follows. 7. <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" backgroundColor="#000000" backgroundAlpha="0" </mx:Application> 11. Between the Application container tags, add an Image component with a source property that points to the header. jpg file in the assets/ fStop directory. The code should appear as follows. <mx:Image source="assets/fstop/header.jpg"/> 12. .Run the application. You should see the main application with the fStop header.

Create the Home component


13. In the Lab1 project in the Navigator view, right-click on the views folder in the src folder at the root of the project and then select New > MXML Component. 14. Supply the following information. Filename: Home. mxml Based on: VBox Remove the values from the width and height

15. Click Finish. You should see the new Home. mxml file open in Flex Builder. 16. Add an HBox container between the VBox container tags. 17. Nested within the Hbox, add an Image component with a source property that points to the city .jpg file in the assets/fstop directory.

18. Confirm that the code appears as follows. <?xml version="1.0" encoding="utf-8"?> <mx:VBox xmlns:mx=" http://www.adobe.com/2006/mxml "> <mx:HBox> <mx:Image source="assets/fstop/city. jpg" /> </mx:HBox> </mx:VBox>

Pgina 102 de 274

ADOBE FLEX 3 Developing Rich Client Applications 19. Below the HBox container, add an Image component with a source that points to the beach.jpg file in the assets/fstop directory. 20. Confirm that the code appears as follows. <?xml version="1.0" encoding="utf-8"?> <mx:VBox xmlns:mx=" http://www.adobe.com/2006/mxml "> <mx:HBox> <mx:Image source="assets/fstop/city.jpg" /> </mx:HBox> <mx:Image source = "assets/fstop/beach.jpg" /> </mx:VBox> 21. Below the Image component inside the HBox, add a VBox with three nested Text controls, each with a fontSize of 13, a width of 250 and a yellowish color (#F8E5BB ).The text property values for the three Text controls are: At fStop, you can view and purchase unique prints by amateur and professional photographers. Shoppers, you can browse our Gallery to find the perfect evocative images for every room in your office or home. If you are a photographer, go to the Contribute section to upload your files and sell your prints.

22. Confirm that the code appears as follows. <mx:HBox> <mx:Image source="assets/fstop/city.jpg"/> <mx:VBox> <mx:Text fontSize="13" width="250" color="#F8E5BB" text="At f-Stop. .." /> <mx:Text fontSize="13" width="250" color="#F8E5BB" text="Shoppers.. . . " /> <mx:Text FontSize="13" width = "250" color="#F8E5BB" text="If you are... " /> </mx:VBox> </mx:HBox >

Pgina 103 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Instantiate the Home component from the main application


23. Return to FStop.mxml and add an XML namespace declaration named v, set to -views. *. The code should appear as follows: <mx:Application xmlns: mx="http://www.adobe.com/2006/mxml" layout ="vertical" BackgroundColor = "#000000" backgroundAlpha ="0" xmlns:v="views.*"> 24. Below the Image component, add an instance of the Home component giving it an id of Home and a label of Home. The code should appear as follows: <v:Home id="home" label="Home" / >

25. Run the application. You should see the Home components content appear in the main application display.

Figure 1: fstop application Home content

Part 2: Creating the Contribute page component


In this part of the lab, you will perform the following tasks: Create a custom component Create a Form in Design mode Instantiate the custom component from the main application MXML file

Pgina 104 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Steps
Create the custom component
1. 2. 3. Create a new MXML component based on the VBox container in the views folder of the src folder at the root of the project and name it Contribute.mxml. Make sure that no height property is specified and the width value is set to 515 pixels. Between the VBox container tags, add an Image component with a source property that points to the tulips.jpg file in the assets/fstop folder.

Create and Populate the Form control


4. Above the Image component, add a Form control with a width set to 100%, fontSize set to 11 pixels with a backgroundColor set to yellowish (#F8E5BB). For the first element in Form control, add a Label control with a text value of Enter your information and upload a file to the gallery. Switch to Design mode. Add a TextInput control below the Label control and set its width to 284 pixels.

5. 6. 7.

Figure 2: Inserting the Text Input correctly

8.

Check to be sure that a FormItem layout container is automatically added.

Figure 3: The inserted Formltem

9.

Change the Formltem container's label property to Photographer:.

10. Add a TextArea control below the TextInput control and set its width to 284 pixels. Be sure to use the blue indicator bar to ensure that it spans the entire Formltem and TextInput control.

Figure 4: Inserting the TextArea

Pgina 105 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Change the Formltem containers label to Description:.


11. Add a ComboBox control below the TextArea control and change its FormItem containers label to Category:. 12.Add a TextInput control with a Width of 284 pixels below the ComboBox control and change its FormItern container's label property to Image:. 13. Select the Image FormItem container and switch to Category View in the Flex Properties view of Flex Builder.

Figure 5: The Image Formltem selected and Category View

14. In the Common section, change the direction value to horizontal. 15. Add a Button control to the right of the Textlnput control in the Image Formltem container.

Figure 6: Inserting a Button to the right of the Textlnput

16. Change the Button label to Browse. 17. Select the Image Formltem container's Textlnput control and in the Common section of the Flex Properties view, select false from the Editable dropdown. 18. Add a Button control below the Image Formltem container. 19. Change the Button control's label to upload. 20. Double click the Formltem container which selects the label contents and delete it.

Figure 7: Selecting the Formltem's label

21. Be sure your FormItem containing the Button appears as shown here.

Figure 8: The Button Formltem with no label text specified

Call the Contribute component from the main application


22. Return to the FStop.mxml file. 23. Below the Home component tag, add an instance of the Contribute component with an id of contribute and a label of Contribute. The code should appear as follows.

Pgina 106 de 274

ADOBE FLEX 3 Developing Rich Client Applications <v:Contribute id="contribute" label="Contribute" />

24. Run the application. You should see the Contribute component content below the Home component content.

Figure 9: fStop application with Contribute content

Part 3: Create the Gallery page component


In this part of the lab, you will perform the following tasks: Create a custom MXML component Use the CheckBox and Combo Box controls Use the Tile container control to tile thumbnail images Instantiate the custom component from within the main application MXML file

Steps
Create the custom component
1. 2. Create a new MXML component based on the VBox container in the views directory and name it Gallery.mxml. Make sure that there is no height property specified and that the width value is set to 515 pixels.

Add the CheckBox and ComboBox controls


Between the VBox container tags, add an HBox container with a yellowish {#F8E5BB) backgroundColor, a width of 100%, a verticalAlign of middle and a fontSize of 11 pixels. 4. Between the HBox container tags, add a Label control with a text value of you are viewing:. 5. Below the Label, add a Checkbox control with a label value of All Photos. 3.

Pgina 107 de 274

ADOBE FLEX 3 Developing Rich Client Applications 6. 7. Below the Checkbox, add a Label control with a text value of The Category. Below the Label, add a ComboBox control with an ArrayCollection as the dataProvider that contains the String values of Abstract, AnimaIs, City, Miscellaneous, Nature and People. The code should appear as follows.

<mx:ComboBox> <mx:dataProvider> <mx:ArrayCollection> <mx:String>Abstract</mx:String> <mx:String>Animals</mx:String> <mx:String>City</mx:String> <mx:String>Miscellaneous</mx:String> <mx:String>Nature</mx:String> <mx:String>People</mx:String> </mx:ArrayCollection> </mx:dataProvider> </mx:ComboBox>

Add the Tile container


Below the HBox, as the last control specified within the custom component, add a Tile container with an id of thumbnails and a Width set to 515 pixels. 9. Open the labl_typing_help.txt file in the views directory and copy all of its content. 10. Paste all the Image components inside the Tile container. Note that each of the Image component has a click event defined which you will use in the next lab. 8.

Instantiate the Gallery component from the main application


11. Return to the FStop.mxml file. 12. Below the call to the Contribute component, call the Gallery component with an id of gallery and a label of Gallery. The code should appear as follows. <v:Gallery id="gallery" Label="Gallery" /> 13. Run the application. You should see the Gallery component content below the Contribute component content.

Figure 10: fStop application with Gallery content

Note: You will get an error message if you click on any of the thumbnail photos. The application will be completed in later labs.

Pgina 108 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Using View States for Application Design


In this section of the course, you will create dynamic application interfaces using the Flex view states.

Objectives
After completing this unit, you should be able to: Create view states using Flex Builders Design mode Create view states using MXML Trigger state changes based on user events Interact with view states defined within custom components

Topics
In this unit, you will learn about the following topics: Understanding view states Controlling view states Reviewing the generated MXML code Creating view states that include custom component states

Pgina 109 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Understanding view states


Important reasons why Flash CS3 and Flex Builder are powerful application development tools To display new content in an HTML page, you would create another page with the new content - HTML works in discrete pages - DHTML allows for more dynamic effects, but is complex to program and maintain Flash applications can be unified applications, which means that the content in the movie can move around or redraw without the need to refresh the page in the browser Traditionally Flash applications were managed - Manually on the timeline - Programmatically via ActionScript Flex introduces view states, which allow developers to easily manage changes in presentation layouts - Components can persist across different tasks - Components can be reconfigured for use in different contexts - Components can be created and managed within Flex Builder with or without writing code

Introducing view states


View states define distinct presentation layouts within the same application Each distinct layout is called a state User or system events are used to change states

Figure 1: Flash an Flex allow you to create dynamic applications that can change their presentation layouts without refreshing the browser windows

View states examples Example #1

Figure 2: An example of different view states used in a e-commerce application

Pgina 110 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Example #2

Figure 3: An example of how view states are used in a search interface

Creating view states


1. 2. Create a base state, which is the default layout of the application or custom component Modify the base state or another state to create additional states Can add, modify or delete components in each state Can modify component properties Can change styles Create events to trigger switching states

3.

Benefits of using view states


Flex manages the switching of states Components can be shared across multiple view states Components can be added, removed, or modified easily

Creating view states within Design mode


Draw-backs to complex unified application development Can be complex to build and maintain Can be hard for a designer to prototype the states due to complex programming Flex Builder Allows designers and developers to quickly and easily create application states Provides individual design mode views to manage states Creating the base state from which additional view states originate Create the base state using Design mode or Source mode as usual Create a component that can trigger the state change via one of its events

Pgina 111 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Figure 4: Here a user action triggers the state change

Creating a new state Switch to Design mode in Flex Builder Right-click on the Base state indicator in the States view (Window > Show View > States) and select New State.

Figure 5: Create a new state using the States view in Flex Builder

In the New State dialog box, name the new state and base it on the base state or another state

Figure 6: You choose an existing state on which to base your new state

Note: You can set the new state to be the state that is displayed when the application starts by checking the Set as start state checkbox. Make sure the new state is selected in the States view and then start adding elements to the view in Design mode - You can add, modify or delete components - You can modify styles - The changes are recorded as part of the new state

States are mutually exclusive only one can be displayed at a time You can base a new state on a state other than the base state You should do this in a case where components are shared by multiple states For instance, the same navigation bar can be displayed by multiple states (these states should be based on the navigation bar state)

Pgina 112 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 1: Creating two states for the Contact page


In this walkthrough, you will perform the following tasks: Create a base state Create a new, additional state

Steps
Import the Viewstates Project
1. 2. Select File > Import > Flex Project. Import project from Archive File Browse to: <installDirectory>/adobeTraining/f3rca/ ViewStatesProject.zip Click Open Click Finish 3. 4. 5. Close all unrelated projects. Open the ViewStates_wt1.mxml file from the src folder at the root of ViewStates project. Run the application. You should see the Contact Caf Townsend panel with the How to Find Us paragraphs.

Creating the new state


6. 7. 8. 9. 10. 11. 12. Switch to Design mode in Flex Builder. Right-click on the Base state indicator in the States view (Window > States) and select New State... In the New State dialog box, name the new state forms and click OK Open the file ViewStates_wt1_typing_help.mxml and switch to Design mode. Select the HBox that contains both forms and copy it. Return to the forms state view in ViewStates_wtl .mxml in Design mode and paste the HBox. Select the HBox and drag it into the panel below the Send an e-mail or request a brochure LinkButton control, using the blue indicator bar to position it.

Figure 7: Drag the form into the panel

13. Select the LinkButton control in the forms state and delete it. The LinkButton control still exists in the Base state.

Pgina 113 de 274

ADOBE FLEX 3 Developing Rich Client Applications 14. Select <Base state> from the States view. You should see the Panel container without the form. Note that the Panel container does not resize to its original width. 15. Select the Panel container in the Base state and set its width to 400 pixels. 16. Select the forms state from the States view. You should see the Panel container with the form. However, the width of the Panel container is too small. 17. Select the Panel container in the forms state and set its width to 700 pixels. 18. Run the application. You should see the panel without the form.

Controlling view states


State implementation details To change states, set the currentState property value to the name of the state to switch to Note: States can be derived from other states as well as from the base state. Flex figures out everything that needs to change between any two states The Base state doesnt have to be the initial state State changes are triggered by events Because Flex always starts from the base view state when it applies a new view state, it is more efficient to use the most commonly used state as the base state Setting currentState - Setting the currentState property of the Application tag sets the initial state to one other than the base state - A component's currentState property specifies its view state - To specify the base view state, set currentState equal to an empty string - In the event handler of a component, set the currentState property equal to the name of a view state to switch to

<mx:Button id="b1" label="Add a Button" click="currentState='newButton'"/> <mx:Button id="b2" label="Remove Added Button" click="currentState=''"/> In Flex Builder, select the component that will trigger the event and set its click event using the Common properties section of the Flex Properties view

Figure 8: Declare which state to switch to when to user clicks by setting its name in the currentState property

Pgina 114 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 2: Switching states in the Contact form


In this walkthrough, you will perform the following tasks: Set the currentState property in the controls click event handler to switch between the two states you created in the last walkthrough

Steps
1. 2. Open the ViewStates_wt2.mxmI file from the src folder at the root of the project. Run the application. You should see the application as it was after the last walkthrough.

Trigger the forms state transition


3. 4. 5. In Flex Builder, make sure you are in Design mode. Select the link button Send an e-mail or request a brochure which is found in the Base state. In the Flex Properties view, click on the Category View button.

Figure 9: See more LinkButton properties using the Category View sort

6.

Locate the Click event in the Events section and set the currentState property to the forms state in the Value column.

The code should appear as follows: click="currentState='forms'"

Return to the forms state


7. 8. Select the forms state in the States view. Select the Send Message button and set its Click event to revert to the base state.

The code should appear as an empty string: click="currentState=''" Notice that there is no space between the single quotes. 9. Also set the Send Request button's click event to revert to the base state. 10. Run the application and click on the link button. You should see the form state of the Contact Caf Townsend panel. 11. Click on either button to return to the Base state.

Pgina 115 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Reviewing the generated MXML code


The MXML tags used to manage view states are The states tag wraps all of the states in single block of code The State tag wraps the details of one individual state The AddChild tag nested within the State tag to instruct that a component be added to the Base state when creating the current state The RemoveChild tag nested within the State tag to instruct that a component be removed from the Base state when creating the current state The SetProperty tag nested within the State tag used to change a property of a component in the current state that originally was created in another state The SetEventHandler tag nested within the State tag to set event handlers which are only active during a particular view state Sample code <?xml version="1.0" encoding = "utf-8"?> <mx:Application xmlns:mx="http:// www.adobe.com/2006/mxml"> <mx:states> <mx:State name="forms" > <mx:AddChild relativeTo="{panel1}" position ="lastChild"> </mx:AddChild> <mx:RemoveChild target="{text1}"/> <mx:SetProperty target="{text2}" name="width" value="370"/> </mx:State> <mx:State name="maps" basedOn="forms") <mx:RemoveChild target="{formiteml}"/> <mx:RemoveChiId target="{formitem2}"/> <mx:AddChild relativeTo="{panel1} position="before"> </mx:AddChild> </mx: State) </mx:states) Base state code here </mx:Application>

Code explanation The states tag is the outermost tag that contains all of the States of the application One or more State tags are placed within the states tag to define each individual state - The name property of the State tag declares the name of the state in question - State names are required and each must be unique for a given component - The basedOn property of the State tag defines which state the state in question is based upon (default is the Base state) - When Flex changes states, it first restores the base State, then applies any changes from the base State determined by the State class basedOn property, then finally applies the changes defined in the new State Within each State tag, one or more AddChild or RemoveChild tags are used to outline the changes, or overrides, between the base State and the State currently being defined - Each component that is added to the state is represented with an AddChild tag - Each component that is removed from the state is represented with a RemoveChild tag Note: If the affected component does not have a declared id property, Flex will automatically create one for it.

Pgina 116 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Using the AddChild tag


The relativeTo and position properties of the AddChild tag are used together to specify into which container to place the child and where the child belongs relative to the container relativeTo property determines the parent container for the child position property determines placement of the child in relation to the parent container

The values for the relativeTo property can be The parent of the state (default) If no relativeTo value is defined, then Flex will determine the position of the child element relative to the main application or custom component, whichever the states component is in A specified component in the application or custom component Bind to the id property of the component <mx:AddChild relativeTo="{contentPanel}"> ... </AddChild> The values for the position property can be before - place the child before the component declared in the relativeTo property after - place the child after the component declared in the relativeTo property firstChild - place the child as the first element in the component declared in the relativeTo property lastChild (default) - place the child as the last element of the component declared in the relativeTo property Do not use the before or after value of the position property if you do not declare a relativeTo property - If you do, the children will be placed, overlapping, in the upper left corner of the application or custom component Do not use the firstChild or lastChild value of the position property if the relativeTo property is not a container - If you do, the child will not appear in the application Main Application < default relativeTo value points here

Figure 10: The relativeTo and position properties of the AddChild tag work together to determine where child elements of a state are placer

Pgina 117 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Using the RemoveChild tag


The target property of the RemoveChild tag specifies the id property of the component to remove

Using the SetProperty tag


The target property of the SetProperty tag specifies the id property of the component whose property is to be changed The name property of the SetProperty tag specifies the name of the component property to be changed The value property of the SetProperty tag specifies the value for the property to be changed

Using the SetEventHandler tag


The target property of the SetEventHandler tag specifies the id property of the component that dispatches the event The name property of the SetEventHandler tag specifies the name of the event that will trigger the event handler The handler event of the SetEventHandler tag specifies the event handler function to execute in response to the event that is specified in the name property

Pgina 118 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 3: Implementing view states using MXML


In this walkthrough, you will perform the following tasks: Create an additional state for the application using MXML Add a Text control to the new state Trigger a state change from the base state to the new state Increase the image size when the user mouses over it Decrease the image size when the user mouses out of it

Steps
7. 8. Open the ViewStates_wt3.mxml file from the src folder at the root of the project. Run the application. You should see an image of the soup appetizer.

Create a state
9. In Flex Builder Source mode, create a States tag block above the Image tag but below the Application tag. The code should appear as follows: <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" backgroundColor="#ffffff" backgroundAlpha="0"> <mx:states> </mx:states> <mx:Image source="assets/app_butternut_soup.jpg"/> </mx:Application>

10. Inside the states tag, create a State tag block. Name the new state details. The code should appear as follows. <mx:states> <mx:State name="details"> </mx:State> </mx:states>

Add Text controls to the new state


11. As a child of the State component, create an AddChild tag set with a position of lastChild. 12. Add a Text control with the text property Roasted Butternut Squash Soup, a width of 200 and a fontWeight of bold. The code should appear as follows,

Pgina 119 de 274

ADOBE FLEX 3 Developing Rich Client Applications

<mx:State name = "details "> <mx:AddChild position="lastChild"> <mx:Text Text="Roasted Butternut Squash Soup" width="200" fontWeight="bold" /> </mx:AddChild> </mx:State> 13. Below the first AddChild tag set, add a second AddChild tag set having a description Text control with the text value of Creamy, rich and silky finished with a touch of fresh basil and smoked walnuts, and a width of 200. The code should appear as follows: <mx:State name="details"> <mx:AddChild position="lastChild" > <mx:Text text="Roasted Butternut Squash Soup" width="200" fontWeight="bold" /> </mx:AddChild> <mx:AddChild position="lastChiId"> <mx:Text text="Creamy, rich and silky finished with a touch of fresh basil and smoked walnuts." width="200"/> </mx:AddChild> </mx:State>

Trigger the State change


14. Update the Image tag to include an id value of soup and set the rollOver event's handler to currentState='detaiIs'. The code should appear as follows: <mx:Image id="soup" source="assets/app_butternut_soup.jpg" rollOver="currentState='detaiIs'" /> 15. Add a SetEventHandler tag as the last tag within the State tag block. Set the target to the soup id property, the name property to rollOut and the handler property back to the base state. The code should appear as follows: <mx: State> <mx:SetEventHandler target="{soup}" name="rollOut" handler="currentState=''"/> </mx:State>

Pgina 120 de 274

ADOBE FLEX 3 Developing Rich Client Applications Notice that there is no space between the single quotes. 16. Run the application. You should see the text appear when the mouse rolls over the image and disappear when the mouse rolls out of the image which reflects the underlying state change that has taken place.

Change the scale property of the image


17. Below the SetEventHandler tags, create two SetProperty tags, both targeted to the soup id property of the Image tag. Set the name properties for the tags to scaleX and scaleY, respectively. Set their value properties to 1.25, in other words, 25% larger. The code should appear as follows: <mx:State> <mx:Set EventHandler target="{soup}" event="rollout" handler="current State=' '"/> <mx:SetProperty target="{soup}" name="scaleX" value="1.25"/> <mx:SetProperty target="{soup}" name="scaleY" value="l.25"/> </mx:State>

18. Run the application. You should see the image appear larger when the mouse rolls over the image and return to its original size when you roll out.

Creating view states that include custom component states


Consider creating custom components when states can be consolidated into discrete units of display and functionality

Figure 11: Custom components can define view states which are then accessible from the main application

Pgina 121 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Creating view states within a custom component The same rules you have learned for creating view states in an application apply to creating them in a custom component

Walkthrough 4: Using custom components with their own view states


In this walkthrough, you will perform the following tasks: Integrate two components view states into the application Use Flex builder to switch the view state Trigger the change in state based on user mouseOver and mouseOut of the panels

Steps
1. 2. Open the ViewStates_wt4.mxml file from the src folder at the root of the project. Run the application. You should see the two custom components displayed. The About component is on the left and the Contact component is on the right.

Set the Contact component to its expanded state


3. 4. In Design mode, select the About component on the stage. Then select the DVD state from the State dropdown of the Common properties in the Flex Properties view.

Figure 12: Select the custom component state to switch to

5. 6.

Refresh the Design mode view if necessary. Run the application. You should see the same custom components displayed, except now the Contact component is expanded to its DVD state by default.

Create the Contact state


7. 8. 9. Right-click on the Base state in the States view and choose New State. Name the new state Contact and click OK. Select the About component and use the States dropdown in the Flex Properties view to switch it back to the <Start state>. 10. In the Layout area of the Flex Properties view, change the component width to 156 and the height to 507. 11. Then select the Contact component. 12. Select the forms state from the State dropdown of the Common properties in the Flex Properties view.

Pgina 122 de 274

ADOBE FLEX 3 Developing Rich Client Applications 13. In the Layout area of the Flex Properties view, change the component width to 690 and the height to 507.

Trigger the Contact state


Return to the application Base state by selecting it from the States view. Select the collapsed Contact component on the design surface. Click on the Category View button in the Flex Properties view. Locate the rollOver event in the Events section and set its value to currentState='Contact'. Click on the expanded About component. Set the rollOver event value to currentState='' .Notice that there is no space between the single quotes indicating the base state. 20. Run the application. You should see the states change as you mouse over each custom component. 14. 15. 16. 17. 18. 19.

Summary
View states define distinct presentation layouts within the same application User or systems events can trigger the change between states The easiest way to create view states is to use Flex Builders Design mode Set the currentState property to define which state to switch to from the current state Use the states component to contain all the States in an application file or in a component Use the State tag to create each state Use the AddChild tag to add components to a view state that are not present in the base state Use the RemoveChild tag to remove components from a view state that are present in the base state Use the SetProperty tag to set the value of a specified property of a component in a view state Use the SetEventHandler tag to indicate the handler that will be executed when the corresponding event is dispatched in a view state

Review
1. How does creating a view state in a custom component differ from creating one in the main application MXML file? What is the base state of a view state? How do you set the current State property back to the base state? Can more than one state be displayed at a time? To what does the relativeTo property of the AddChild component refer? Give an example of when you might want to set the basedOn property of the State tag to anything other than the default.

2. 3. 4. 5. 6.

Pgina 123 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Creating Application Navigation


In this section of the course, you will learn how to implement and manipulate navigator containers individually and relative to one another. You will also learn how navigator and layout containers interact.

Objectives
After completing this unit, you should be able to: Understand what navigator containers are and how to create them Navigate the ViewStack container with the LinkBar and TabBar controls Use Button controls to create custom navigation control elements Implement the ApplicationControlBar layout container as a navigation element

Topics
In this unit, you will learn about the following topics: Understanding navigator containers and controls Using the LinkBar control Using the TabBar control Using the ViewStack container Using the TabNavigator container Using the Accordion container Using ButtonBar & ToggleButtonBar Using the ApplicationControlBar container

Pgina 124 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Understanding navigator containers and controls


There are two types of containers Layout containers Control the sizing and positioning of the child elements within them Navigator containers Control user movement, or navigation, among multiple child containers This module discusses only navigator containers Navigator container basics The direct children of a navigator container must be containers, either layout or navigator containers A navigator container has built-in mechanisms to allow user driven or programmatic movement through a group of child containers Typical properties of a container tag include id, width, and height A specified component id property enables access to its properties, methods and events at runtime via ActionScript Navigator containers are implemented as a hierarchy in an ActionScript class library - Sprite > FlexSprite > UIComponent > Container > All Containers The navigator containers and controls are Container Accordion ButtonBar LinkBar TabBar TabNavigator ToggleButtonBar ViewStack Description Organizes information in a series of child panels, where one panel is active at any time Defines a group of logically related buttons with a common appearance and navigation behavior that do not maintain state Defines a row of LinkButton controls designating a series of linked destinations often used with a ViewStack container Defines a horizontal row of tabs, often used with a ViewStack container Displays a container with tabs to let users switch between different content areas Defines a group of logically related buttons with a common appearance and navigation behavior that maintain state Defines a stack of containers that displays a single container at a time

Navigator containers and their children Only the ViewStack, TabNavigator, and Accordion navigator containers have child containers that you can layout The LinkBar, ButtonBar, and TabBar navigator controls do not have child containers Instead, they enable users and code to control the currently active child container of a ViewStack container

The individual child containers, not the navigator, control the layout and positioning of their children The ApplicationControlBar container is a layout container that is often used like a navigator container You use the ApplicationControlBar container to hold components that provide access to application navigation elements and commands

Pgina 125 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Using the LinkBar control


The LinkBar control defines a horizontal row of LinkButton controls is a navigator container with built-in logic to switch between children of a ViewStack container has a width that is wide enough to contain all label text plus separators and necessary padding has a height that accommodates the tallest child element has a default padding value on all sides of 2 pixels is represented in MXML with the <mx:LinkBar> tag

Figure 1: A LinkBar navigator for the Cafe Townsend application

One way to populate a LinkBar container is to use a dataProvider property <mx:LinkBar> <mx:dataProvider> <mx:String>Home</mx:String> <mx:String>Contact Us</mx:String> <mx:String>About Cafe Townsend</mx:String> <mx:String>Special Events</mx:String> <mx:String>Restaurant Menu</mx:String> </mx:dataProvider> </mx:LinkBar>

Using the TabBar control


The TabBar control defines a horizontal (default) or vertical row of tabs is a navigator container with built-in logic to switch between children of a ViewStack container has a width that is wide enough to contain all tabs has a height that accommodates the tallest child element has a default padding value on all sides of 0 pixels is represented in MXML with the <mx:TabBar> tag

Figure 2: A TabBar navigator for the Cafe Townsend application

Supplying data to the TabBar control You can use a dataProvider as discussed earlier for the LinkBar control You can use an Object data type instead of a String with a label property If you do not use the label property (when using an Object data type), you can use the labelField property of the TabBar to declare which Object key to use for the tab label display

Pgina 126 de 274

ADOBE FLEX 3 Developing Rich Client Applications <mx:TabBar labelField="menuName"> <mx:dataProvider> <mx:Object menuName="Home" /> <mx:Object menuName="Contact Us" /> <mx:Object menuName="About Cafe Townsend" /> <mx:Object menuName="Special Event" /> <mx:Object menuName="Restaurant Menu" /> </mx:dataProvider> </mx:TabBar>

Using the ViewStack container


The ViewStack container is made up of a collection of child containers that are stacked on top of each other, with only one container visible, or active, at a time does not provide a user interface for selecting which child container is currently visible typically uses the LinkBar or TabBar controls to switch between child containers, although a custom solution can be implemented sets its height and width based on the first active child has all padding values set to 0 is represented in MXML with the <mx:ViewStack> tag

<mx:ViewStack id="cafeTownsendContent"> ... child containers </mx:ViewStack>

Figure 3: Navigating the ViewStack container with TabBar navigator and custom Button controls

Setting the active ViewStack child container


Use the selectedIndex property of the ViewStack container to set which child container is currently active or visible The following code sets the second child container to be initially active <mx:ViewStack id="cafeTownsendContent" selectedIndex="1"> ... child containers </mx:ViewStack>

Pgina 127 de 274

ADOBE FLEX 3 Developing Rich Client Applications Set the selectedIndex property of the ViewStack container in the event handler code for the component that triggers the switching between ViewStack child containers <mx:Button label="Home" click="cafeTownsendContent.selectedIndex=0"/> <mx:Button label="Contact Us" click="cafeTownsendContent.selectedIndex=1"/> The selectedChild property of the ViewStack container is used to specify the container either by id property value or by index <mx:Button id="nextButton" label="Next" click="cafeTownsendContent.selectedChild=myContainerID"/> The numChildren property of the ViewStack container contains the number of child containers in the ViewStack

Revisiting the LinkBar and TabBar containers


Specify the ViewStack container as the value of the dataProvider property of the LinkBar or TabBar control The text displayed on the LinkBar or TabBar control are from the label property of each ViewStack child container You provide only the single dataProvider property to the LinkBar or TabBar control to specify the name of the ViewStack container associated with it <mx:LinkBar dataProvider="{myViewStack}" borderStyle="solid"/>

Displaying and Resizing the ViewStack child containers


ViewStack container display and sizing basics If the child is smaller than the ViewStack container, it is aligned to the upper-left corner of the ViewStack container ViewStack containers are only sized once to fit the size of the first child container by default They do not resize when you navigate to other child containers by default

Only the initial child container is instantiated immediately The others are instantiated when they are requested by the user this is called deferred instantiation With deferred instantiation you can control how container content is loaded Change the default instantiation behavior by setting the values of the container creationPolicy property auto (default) Creates all controls only in the initial view of the navigator container This setting causes a faster startup time for the application, but results in slower response time for user navigation all Creates all controls in all views of the navigator container This setting causes a delay in application startup time, but results in quicker response time for user navigation

Pgina 128 de 274

ADOBE FLEX 3 Developing Rich Client Applications none Instructs Flex to not instantiate any component within the navigator container or any of the navigator container's panels until you manually instantiate the controls queued This property has no effect on deferred creation, but is instead used for ordered creation

You can use the following techniques to control the size of a ViewStack container so that it properly displays all children Set explicit width and height properties for all children to the same fixed values Set the width and height properties for all children to the same percentage values Set width and height properties for the ViewStack container to 100% Refresh the ViewStack display based on the content of the active container by setting the resizeToContent property to true

Enabling Buttons Dynamically


You can use the selectedIndex property to dynamically determine next and previous ViewStack positions <mx:Button label="&lt; previous" click="cafeTownsendContent.selectedIndex--"/> <mx:Button label="&gt; next" click="cafeTownsendContent.selectedIndex++"/> Dynamically control the navigation by using the enabled property to enable and disable user interaction with the buttons <mx:Button label="&lt; previous" click="cafeTownsendContent.selectedIndex--" enabled="{cafeTownsendContent.selectedIndex != 0}"/> <mx:Button label="&gt; next" click="cafeTownsendContent.selectedIndex++ enabled="{cafeTownsendContent.selectedIndex != (cafeTownsendContent.numChildren - 1)}"/> On rare occasions when using the decrement/increment code above, it is possible that timing issues may cause the bindings to fail to execute automatically If this happens, use executeBindings(true) in the creationComplete event of the Application

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml/" layout="vertical" creationComplete="executeBindings(true)">

Pgina 129 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 1: Navigating the Cafe Townsend application using the ViewStack and TabBar control
In this walkthrough, you will perform the following tasks: Implement a ViewStack navigator container Navigate the ViewStack container using a TabBar control

Steps
Import Navigator Project
1. 2. File > Import > Flex Project. Import project from Archive File. Browse to: <installDirectory>/adobeTraining/f3rca/ NavigatorProject.zip Click Open Click Finish Close all unrelated projects. Open the Navigator_wt1.mxml file from the src folder at the root of the project. Run the application. You should see all the content for each container stacked vertically, seemingly haphazardly. Use the scrollbar as necessary to view the page.

3. 4. 5.

Add the ViewStack container tag


6. Return to the application file in Flex Builder's Source mode and review the code with your instructor. You should see a commented block of code with two Button controls and a TabBar control. Ignore that code for now. Notice that each of the following five container code blocks has a label property that defines its Content. 7. Below the commented code, but around the five components, add a ViewStack tag set with an id property of cafeTownsendContent. Also set the width to 700 pixels and all four padding properties to 15 pixels. The code should appear as follows.

<mx:ViewStack id="cafeTownsendContent" width="700" paddingBottom="15" paddingLeft="15" paddingRight="15" paddingTop="15"> ... children container code </mx:ViewStack> 8. Run the application. You should see only the content for the first container, Home. However, this content is displayed within scrollbars.

Pgina 130 de 274

ADOBE FLEX 3 Developing Rich Client Applications

9. Add a resizeToContent property set to true to the ViewStack container. 10. Remove the width property from the ViewStack container. 11. Run the application. You should see the Home content fully displayed.

Associate the ViewStack container children to the TabBar control


12. Uncomment the code block at the top of the page and add a dataProvider property to the TabBar control. Bind the property to the ViewStack container's id property value, cafeTownsendContent. <mx:TabBar dataProvider="{cafeTownsendContent}" /> 13. Run the application. You should see a TabBar with one tab for each of the five containers in the ViewStack. Click on each of the tabs to switch between the ViewStack content. Notice that the tab labels match the labels for each container. Also note the buttons to the left and right of the TabBar.

Create custom button navigation for the ViewStack container


14. In Flex Builder, add a click event to each button inside the HBox container containing the navigation buttons. For the previous button, set the click value to cafeTounsendContent.selectedIndex--. For the next button, set the click value to cafeTownsendContent.selectedIndex++. The code should appear as follows. <mx:HBox horizontalGap="15" > <mx:Button label="&lt; previous" click="cafeTownsendContent.selectedIndex--" /> <mx:TabBar dataProvider="{cafeTownsendContent}" /> <mx:Button label="&gt; next" click="cafeTownsendContent.selectedIndex++" /> </mx:HBox> 15. To dynamically disable the button when the user is on the first tab, add enabled="{cafeTownsendContent.selectedlndex != 0}" to the previous button. 16. To dynamically disable the button when the user is on the last tab, add enabled="{cafeTownsendContent.selectedIndex (cafeTownsendContent.numChildren - 1)}" to the next button. The code should appear as follows. <mx:HBox horizontalGap="15"> <mx:Button label="&lt; previous" click="cafeTownsendContent.selectedIndex--" enabled="{cafeTownsendContent.selectedIndex != 0}"/>

Pgina 131 de 274

ADOBE FLEX 3 Developing Rich Client Applications

<mx:TabBar dataProvider="{cafeTownsendContent} " /> <mx:Button label="&gt; next" click="cafeTownsendContent.selectedIndex++" enabled="{cafeTownsendContent.selectedIndex != (cafeTownsendContent.numChildren - 1)}"/> </mx:HBox> 17. Run the application. You should see the previous button enabled and next button disabled. 18. To fix this timing issue, add a creationComplete property to the Application component with a value of executeBindings(true). The code should appears as follows. <mx:Application xmlns:mx=http://www.adobe.com/2006/mxml layout="vertical" backgroundColor="#ffffff backgroundAlpha="0" creationComplete="executeBindings(true)"/> 19. Run the application. You should now be able to navigate the content using either the TabBar or the previous and next buttons.

Using the TabNavigator container


The TabNavigator container works the same way as the ViewStack container when it comes to setting the active container and displaying and resizing content defines a horizontal row of tabs has its own child content so does not need to specify a ViewStack or dataProvider displays the associated child content when a tab is selected displays only one child of the TabNavigator at a time, in the order they are defined has a width that is wide enough to contain all label text plus separators and necessary padding has a height that accommodates the tallest child element has a default padding value on all sides of 2 pixels is represented in MXML with the <mx:TabNavigator> tag

<mx:TabNavigator id="cafeTownsendContent" width="400" height="200"> ...child containers... </mx:TabNavigator>

Pgina 132 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Figure 4: Navigating the Cafe Townsend application with a TabNavigator container and custom Button controls

When a TabNavigator container has focus, Flex processes keystrokes as described in the following table Key Down Arrow, Right Arrow Up Arrow, Left Arrow Page Down Page Up Home End Enter, Space Action Gives focus to the next tab, wrapping from last to first, without changing the selected child Gives focus to the previous tab, wrapping from first to last, without changing the selected child Selects the next child, wrapping from last to first Selects the previous child, wrapping from first to last Selects the first child Selects the last child Selects the child associated with the tab displaying focus

Using the Accordion container


The Accordion container works the same way as the ViewStack and TabNavigator containers when it comes to setting the active container and displaying and resizing content defines vertically-stacked panels that animate as they open and close has its own child content displays the associated child content when a panel is selected displays only one child of the Accordion at a time, in the order they are defined has a width that is wide enough to container all label text plus separators and necessary padding has a height that accommodates the tallest child element has a default padding value on all sides of 2 pixels is represented in MXML with the <mx:Accordion> tag

Pgina 133 de 274

ADOBE FLEX 3 Developing Rich Client Applications

<mx:Accordion id="cafeTownsendContent" width="400" height="200"> ...child containers... </mx:Accordion>

Figure 5: Navigating the cafeTownsend application with an Accordion navigator container and custom Button controls

When an Accordion container has focus, Flex processes keystrokes as described in the following table Key Page Up Home Home End Action Move to the next child panel, if any Move to the next child panel, if any Move to the first child panel Move to the last child panel

Pgina 134 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 2: Navigating the Cafe Townsend content using the TabNavigator and Accordion containers
In this walkthrough, you will perform the following tasks: Switch the ViewStack container to a TabNavigator container Then switch the TabNavigator container to an Accordion container

Steps
1. 2. 3. Open the Navigator_wt2.mxml file from the src folder at the root of the project. Run the application. You should see the Home page content with the previous and next buttons below it. In Flex Builder's Source mode, review the code with your instructor. You should see the same code as in the last walkthrough except the TabBar control code has been removed and the buttons are at the bottom of the page instead of at the top. Replace the ViewStack container tags with TabNavigator container tags (opening and closing). Run the application. You should see the content now contained in a TabNavigator. Replace the TabNavigator container with the Accordion container. Run the application. You should see the content now contained in an Accordion. Notice that you can still use the previous and next buttons to navigate the content and that the Accordion panel headers are very large. Remove all the padding styles in the Accordion tag. Run the application. You should see the Accordion panel headers are the default size.

4. 5. 6. 7.

8. 9.

Using ButtonBar & ToggleButtonBar


The ButtonBar and ToggleButtonBar controls define a group of logically related buttons with a common appearance and navigation behavior provide a toolTipField property to generate a tool tip display specify data using a dataProvider property define a horizontal row of button controls have a width that is wide enough to display the button controls have a height that accommodates the tallest button control is represented in MXML with the <mx:ButtonBar> or <mx:ToggleButtonBar> tags have one difference. The ToggleButtonBar creates a toggle effect for the buttons. By default, the first button is depressed when state is maintained

Figure 3: The ToggleButtonBar control holds buttons that can maintain state

<mx:ButtonBar> <mx:dataProvider> ... </mx:dataProvider> </mx:ButtonBar>

Pgina 135 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Using the ApplicationControlBar container


The ApplicationControlBar container Is a layout, not navigator container, but is often used to hold application navigational elements and commands Is usually placed at the top of the application Can be in docked mode or normal mode Has a width that is wide enough to contain all children when in normal mode Is as wide as the application in docked mode Has a height that accommodates the tallest child element Has a default padding value on all sides of 8 pixels Has a default direction of horizontal Is represented in MXML with the <mx:ApplicationControlBar> tag

Figure 7: ApplicationControlBar

The ApplicationControlBar modes Docked mode The bar is always at the top of the application's drawing area Any application-level scroll bars don't apply to the container, so that it always remains at the top of the visible area, and the bar expands to fill the width of the application To create a docked control bar, set the dock property of the ApplicationControlBar container to true

Normal mode The bar can be placed anywhere on the application and scrolls with the application In this mode, users cannot move the bar arbitrarily or float the bar over the application The bar floats only in the sense that it can scroll with the application To create a normal control bar, set the dock property of the ApplicationControlBar container to false (the default)

Pgina 136 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 3: Adding the ApplicationControlBar container to the Cafe Townsend application


In this walkthrough, you will perform the following tasks: Add an ApplicationControlBar container to the Cafe Townsend application to hold navigation and other controls Add a ToggleButtortBar control to switch font sizes

Steps
1. 2. Open the Navigator_wt3.mxml file from the src folder at the root of the project. Run the application. You should see the application content contained within a ViewStack container and a LinkBar control at the top of the application to control the navigation between the ViewStack child containers.

ApplicationControlBar container
3. 4. In Flex Builder's Source mode, insert an ApplicationControlBar around the LinkBar control. Give it a horizontalAlign style of center and a dock property of true. Run the application. You should see the LinkBar is docked at the top of the application.

Add a ToggleButtonBar container


5. Add a ToggleButtonBar control with a horizontalGap style of 5 pixels below the LinkBar control in the ApplicationControlBar container. Use the dataProvider child tag to define three buttons labeled small font, medium font and large font, respectively. The code should appear as follows.

<mx:ApplicationControlBar horizontalAlign ="center" dock=" true"> <mx:LinkBar dataProvider="{cafeTownsendContent}"/> <mx:ToggleButtonBar horizontalGap="5"> <mx:dataProvider> <mx:Array> <mx:Object label="small font" /> <mx:Object label="medium font" /> <mx:Object label="large font" /> </mx:Array> </mx:dataProvider> </mx:ToggleButtonBar> </mx:ApplicationControlBar> 6. Run the application. You should three buttons to the right of the links. Notice that the first one is toggled on by default.

Pgina 137 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Summary
There are two types of containers - layout and navigator Navigator containers do not directly contain content Nest layout containers, with child controls, inside a navigator container A ViewStack container requires other navigator containers, like the LinkBar or the TabBar, to provide navigation among its child containers Bind the ViewStack containers id property to the LinkBar or TabBar controls dataProvider property to use the ViewStack containers nested layout containers as the menu items Use the selectedIndex or selectedChild property to determine which layout container within the navigator container should be active Use the executeBindings(true) method only if bindings do not execute automatically The navigator containers can utilize the dataProvider property to define the menu items The ApplicationControlBar is not a navigator container but is often used in a similar manner

Review
1. 2. 3. 4. How do you create a docked vs normal ApplicationControlBar? What does the creationPolicy of component dictate? Describe the physical differences between the TabBar and TabNavigator? What property of the navigator container references the name of the currently selected nested layout container?

Pgina 138 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Customizing the Application


In this section, you customize the look and feel of Flex applications with styles, behaviors and transitions.

Objectives
After completing this unit, you should be able to: Modify the default Flex application style Add animations to components using triggers and effects Add animations to view state transition with effects

Topics
In this unit, you will learn about the following topics: 1. 2. 3. 4. 5. Customizing Flex application look and feel Modifying Styles to change look-and-feel Using Themes Applying behaviors to components Applying transitions to view state changes

Pgina 139 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Customizing Flex application look and feel


You can modify almost every aspect of the look-and-feel and user interaction of your application by using these features of Flex Component sizes Height and width of a component or application (this topic has been discussed in other modules of the course so it will not be discussed again here) Graphical display Characteristics like color, font size, border widths, text alignment, corner radius settings and many more Dynamic effects Animation or sound applied to Flex display elements based on application or user triggers Fonts Default or embedded text character sets (this topic is outside the scope of this module)

In this module we focus on these features Graphical display Styling or customizing the application UI Dynamic effects Behaviors to add animation and motion to your application Transitions to play effects when a view state change occurs

Changing Flex control style defaults


What are skins and styles? Skins are graphics displayed on components For example, the down arrow of the ScrollBar component is made up of three skins ScrollDownArrowDisabled ScrollDownArrowUp ScrollDownArrowDown Some components share skins Example - components that use scroll bars - including all containers - share their skins with the ScrollBar component

Styles are defined on components You can customize these styles (and add your own)

Figure 1: Use styles update the look-and-feel of your Flex applications

Pgina 140 de 274

ADOBE FLEX 3 Developing Rich Client Applications

There are three ways to change the appearance of components Use the Styles API to programmatically modify styles Physically modify or replace a skin Apply a theme made up of styles and skins (not covered)

Interacting with users using animated effects


What are behaviors and transitions? Behaviors are a pairing of a trigger with an effect Transitions are effects that play when a view state change occurs Content is most important in your application Animation is often considered to be unnecessary Sometimes animations help the user experience, especially in dynamic presentation interfaces Transitions can help users track where elements have moved on the screen Slight movement and animation can help maintain a dialogue with the user Effects can subtly suggest to users what elements are interactive

Modifying Styles to change look-and-feel


Flex provides several ways of setting component styles using MXML component properties calling the setStyle() method in ActionScript using cascading style sheets (CSS) setting global styles implementing a built-in theme style

Setting styles inline using MXML component attributes


You have already set some styles for components by specifying values for attributes in MXML components <mx:Text text="Appetizers" color="#dd7142" /> Style applied directly to one particular component instance

Setting styles in ActionScript for individual components using the setStyle() method
Component users can use the setStyle() method to set a style on a component emailButton.setStyle("fontSize", 15);

Pgina 141 de 274

ADOBE FLEX 3 Developing Rich Client Applications

The setStyle() method is one of the most resource-intensive calls in the Flex Framework The call requires notifying all the children of the newly styled object to do another style lookup The resulting tree of children that must be notified can be quite large In general, you only need the setStyle() method when you want to change styles on existing objects Do not use it when setting up styles for an object for the first time Instead, set styles in an Style block, through an external CSS style sheet, or as global styles

Understanding ActionScript vs. CSS styles


Flex supports a subset of the styles that are available in CSS Flex controls also have unique styles that are not defined by the CSS specification Multiword style names cannot include hyphens in ActionScript or MXML If you use a hyphenated style in either of these cases, Flex will ignore that style In a Style block you can use either syntax Examples of equivalent CSS and ActionScript styles CSS style font-weight font-style font-family color ActionScript style fontWeight fontStyle fontStylefontFamily color

Inline MXML styles must use ActionScript style naming syntax Either CSS or ActionScript style naming syntax can be used within a Style block Flex enforces style settings and throws compilation errors if you try to apply a style that is not supported by the component <mx:LinkButton label="Send an e-mail or request a brochure" borderStyle="solid" />

Figure 2: Rather than failing silently, Flex will throw a compilation error when it cannot resolve styles

Setting styles using Cascading Style Sheets (CSS)


Creating CSS type selectors Type selectors assign styles to all instances of a particular type Within the Style container, name the MXML component and define its styles

Pgina 142 de 274

ADOBE FLEX 3 Developing Rich Client Applications

<mx:Style> TextArea {backgroundColor:"0x0000FF"} </mx:Style> <mx:TextArea id="Message" /> Use a comma-separated list of components to set the same style to all specified component types

<mx:Style> Button, TextInput, Label { font-style: italic; } </mx:Style> Creating CSS class selectors Class selectors define a set of styles (or a class) that you can apply to any component Within the Style tag, first create a CSS class selector and define its styles Then apply the style without the leading period to an MXML component using the styleName property

<mx:Style> .headerText { color: #854230; font-family: Arial; } </mx:Style> <mx:Text styleName="headerText" text="Appetizer" /> Note: Some controls have styles that reference specific CSS class selectors. For example, the Panel container has a style named titleStyleName, which bye points to CSS style named windowStyles. If you do not have a CSS class selector named windowStyles, by default the Panel's title will be set to bold. If you create a CSS class selector named windowStyles, the styles you define in it will bet to the Panels title. Consider the following code: .windowStyles{ color:#ffffff; } Using the CSS global selector Define styles of the special global selector to apply to all components <mx:Style> global { color: #009900; fontSize: 12; } </mx:Style> You can import an external CSS file using the source property of the Style container component <mx:Style source="cafeTownsendStyles.css" />

Pgina 143 de 274

ADOBE FLEX 3 Developing Rich Client Applications

If you set the source property Contents of that particular Style component body must be empty However, multiple Style tags are allowed You should try to limit the number of style sheets used in an application, and set the style sheet only at the top-level document in the application (the document that contains the Application container) If you set a style sheet in a child document, unexpected results can occur Inheritance exceptions Not all styles are inheritable, and not all styles are supported by all components and themes In general, color and text styles are inheritable All other styles are not inheritable unless otherwise noted A style is inherited only if it meets the following conditions The style is supported by the theme (themes are discussed later in this module) The style is inheritable The style is supported by the component The style is set on the component's parent container or the container's parent The style is not overridden at a lower level (remember, a type selector can be overridden by an inline style) You can apply noninheritable styles to all controls using the global selector

Style Precedence order (highest precedence first) 1. The style defined by any inline style 2. The style defined by any class style 3. The style defined by any type style 4. The style defined inline for a parent container 5. The style defined by a class for the parent container 6. The style defined by a type selector for the parent container 7. A globally defined style You can create compound style declarations by mixing class and type selectors

<mx:Style> Text { font-size: 10pt; } .headerText { color: Blue; } </mx:Style> <mx:Text styleName="headerText" text="Appetizer" /> You can use embedded resources in your Style blocks This is useful for styles such as backgroundImage, which you can apply to an embedded resource such as an image file or font

Pgina 144 de 274

ADOBE FLEX 3 Developing Rich Client Applications

<mx:Style> .textBackground { backgroundImage: Embed("images/purpleGradient.gif"); } </mx:Style> <mx:HBox> <mx:TextArea width="200" height="200" styleName="textBackground" /> </mx:HBox>

Styling Button States


Many controls such as the Button and others have multiple states that indicate user interaction Each Button state can be individually styled or skinned with an image so that the control appears different as the user interacts with the control Specify images for up to eight different Button states: up, over, down, disabled, selected up, selected over, selected down and selected disabled Use the skin properties to modify the background and border of the button essentially making the image into the button

<mx:Button id="myButton" downSkin="@Embed('assets/expand.swf')" upSkin="@Embed('assets/collapse.swf')" overSkin="@Embed('assets/collapse_red.swf')" />

Figure3: Button using an image skin

Use the icon properties to display an image on the button <mx:Button id="myButton" downIcon="@Embed('assets/expand.swf')" upIcon="@Embed('assets/collapse.swf')" overIcon="@Embed('assets/collapse_red.swf')" />

Figure4: Button using an image icon

Pgina 145 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Use the toggle property to allow the Button state to remain selected or unselected until it is clicked again <mx:Button id="myButton" toggle="true" upSkin="@Embed('assets/collapse.swf')" downSkin="@Embed('assets/expand.swf')" selectedUpSkin="@Embed('assets/expand.swf')" selectedOverSkin="@Embed('assets/expand.swf')"/>

Using Themes
Flex provides several themes that can be applied to the overall application Use the themeColor style to set the theme color to any color or to a halo color (haloGreen, haloBlue, haloSilver, haloOrange)

<mx:Application themeColor="haloBlue"> It is recommended that you only set theme information at the application level rather than the control level

Pgina 146 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 1: Changing the look and feel of the Caf Townsend application
In this walkthrough, you will perform the following tasks: Add inline styles Add global selector font styles Add a class selector for the menu header style Add a type selector that applies to all Panels Change a components theme color

Figure 5: The cafe Townsend application before and after styles and themes are applied

Steps
Import the Customize Project
1. 2. Select File > Import > Flex Project Import project from Archive File. o Browse to: <installDirectory>/adobeTraining/f3rca/ CustomizeProject.zip o Click Open o Click Finish Close all unrelated projects. Open the Customize_wt1.mxml file from the src folder at the root of the Customize project. Run the application. You should see the Caf Townsend application.

3. 4. 5.

Pgina 147 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Add inline styles to the VBox container


6. 7. 8. In Source mode, locate the VBox container that surrounds the three Panel containers and change the verticalGap style to 15 pixels. Add paddingRight and paddingBottom styles to the VBox container with a value of 8. Run the application. You should see looser padding around the Panel containers.

Add global selector styles using the Style component


At the top of the application file below the opening Application container tag, add a Style component. 10. In the Style component body, create a global selector. You can use Ctrl-space to display stylenames. 11. Set the fontSize style equal to 11. 12. Set the font- family style equal to Arial. The code should appear as follows. 9. <mx:Style> global { fontSize: 11; font-family: "Arial"; } </mx:Style>

13. Run the application. You should see that all text in the application now is set to the Arial font. Some of the text may appear smaller due to the Arial font style.

Add a custom headerText class selector


14. At the end of the Style body, create a custom Class selector named headerText. 15. Set the color style to a shade of blue (#009EEA). 16. Set the fontSize style to 13. The code should appear as follows. .headerText { color:#009EEA fontSize :13; } 17. Apply this class selector to each of the three Menu section header Text controls using the styleName property. The code should appear as follows. <mx:Text text="Appetizers" color="#dd7142" fontWeight="bold" styleName="headerText" />

Pgina 148 de 274

ADOBE FLEX 3 Developing Rich Client Applications <mx:Text text="Entrees" color="#dd7142" fontWeight="bold" styleName="headerText" /> <mx:Text text="Desserts" color="#dd7142" fontWeight="bold" styleName="headerText" />

18. Run the application. You should see that the menu section headers are still the same burnt orange color as before due to the presence of the higher precedence inline style. 19. Remove the color styles in each of the Text controls. 20. Run the application. You should see that the CSS Class selector is now applied and the menu section headers are now blue.

Add a Panel Type selector to affect all panels


21. 22. 23. 24. 25. At the end of the Style block, create a Type selector for the Panel container. Set the borderAlpha style to 1. Set the headerColors array style to the two shades of gray, #E7E7E7 and #D9D9D9. Set the roundedBottomCorners style to true. Set the cornerRadius style to 15. The code should appear as follows.

Panel { borderAlpha: 1; headerColors: #E7E7E7, #D9D9D9; roundedBottomCorners: true; cornerRadius: 15; } 26. Run the application. You should see that all three Panel containers show their title bars with gray borders and have rounded corners. Click on the first menu scrollbar to see that it has a default haloBlue theme look and feel.

Change the theme color for the application components


27. Add the themeColor style to the Application container and set its value to haloOrange. 28. Run the application and click on the first scrollbar. You should see that the halo effect is now orange when you click on one of the scroll bars.

Applying behaviors to components


Behaviors let you add animation and motion to your application components in response to some user or programmatic action For example, you can create a behavior for a Label component that causes it to fade out when the user passes the mouse over it

Pgina 149 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Understanding behavior basics


Behaviors have two parts A trigger An action, such as a user clicking on a button, a component gaining focus, or a component becoming visible An effect A visible or audible change to the component occurring over a period of time such as a Fade effect Components have triggers, but they do not do anything until you associate them with an event Triggers are not events For example, a Button has both a mouseDownEffect trigger and a mouseDown event Triggers initiate Effects Events specify the event handler that is executed when a user initiated event is dispatched Multiple effects can play based on a single trigger For example, when a user clicks on a button, a window can be resized while at the same time moving to another location on the screen

Reviewing available Effects


The following table lists the Effect classes that Flex supports Note: Effect properties are not listed in the table below. Look to the Flex Builder Help documentation for details. Search for the particular effect name.

Effect AnimateProperty

Blur Dissolve Fade Glow Iris

Move Pause Resize Rotate

SoundEffect WipeLeft WipeRight WipeUp WipeDown Zoom

Description Animates a numeric property of a component Sample properties are: height, width, scaleX, or scaleY You specify the property name, from value, and to value of the property to animate Applies a blur visual effect to a component Modifies the alpha property of an overlay to gradually have the target component appear or disappear Animates the component from transparent to opaque, or from opaque to transparent Applies a glow visual effect to a component Animates the effect target by expanding or contracting a rectangular mask centered on the target The effect can either grow the mask from the center of the target to expose the target, or contract it toward the target center to obscure the component Changes the position of a component over a specified time interval Does nothing for a specified period of time Changes the width and/or height of a component over a specified time interval Rotates a component around a specified point You can specify the coordinates of the center of the rotation, and the negative or positive starting and ending values for the angle of rotation Plays an MP3 audio file Defines a bar wipe effect The before or after state of the component must be invisible

Zooms a component in or out from its center point

Pgina 150 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Defining behavior triggers


The following table describes the effect that corresponds to each trigger Trigger addedEffect creationCompleteEffect focusInEffect focusOutEffect hideEffect mouseDownEffect mouseUpEffect moveEffect removedEffect resizeEffect rollOutEffect rollOverEffect showEffect Description Component is added as a child to a container Component is created Component gains keyboard focus Component loses keyboard focus Component becomes invisible by changing the visible property of the component from true to false User presses the mouse button while the mouse pointer is over the component User releases the mouse button Component is moved Component is removed from a container Component is resized User rolls the mouse pointer off the component User rolls the mouse pointer over the component Component becomes visible by changing the visible property of the component from false to true

About applying behaviors


Apply a simple behavior by setting the trigger name property of the component to the name of the effect class <mx:Button id="sendButton" label="Send Message" mouseDownEffect="Fade" /> You cannot declare other Effect properties when you define the effect inline with the component The particular Effect will execute using default values Define a reusable effect instance First use the MXML component for the effect <mx:Fade id="fadeEffect" /> Then apply the effect to the targets using data binding

<mx:Button id="sendButton" label="Send Message" mouseDownEffect="{fadeEffect}" /> <mx:Button id="requestButton" label="Request Brochure" mouseDownEffect="{fadeEffect}" /> When the effect is declared separately from the component, you can declare its associated properties inline

<mx:Fade id="fadeEffect" alphaFrom="1" alphaTo="0" /> Set the duration property of an effect to instruct Flex to perform the Fade effect over the specified number of milliseconds

Pgina 151 de 274

ADOBE FLEX 3 Developing Rich Client Applications <mx:Fade id="fadeEffect" alphaFrom="1" alphaTo="0" duration="1000" /> You can set multiple triggers and effects to the same target <mx:Fade id="fadeOut" alphaFrom="1" alphaTo="0" duration="1000" /> <mx:Fade id="fadeIn" alphaFrom="0" alphaTo="1" duration="1000" /> <mx:Button id="sendButton" label="Send Message" mouseDownEffect="{fadeOut}" mouseUpEffect="{fadeIn}"/>

Assign effects to triggers using Flex Builder Select the component in the editor's Design mode by clicking it on the page Select a trigger for the effect in the Effects category of the Flex Properties view Associate an effect with the trigger by entering the name of the effect in the field next to the trigger name

Figure 6: Assigning effects to a trigger using Flex Builder

Creating parallel and sequential effects


You can apply multiple effects Use Parallel or Sequence components Parallel effects occur simultaneously on the target Sequential effects occur one after the other You can nest Parallel and Sequence components inside one another to generate more complex animations

<mx:Parallel id="moveAndFadeParallel"> <mx:Move xFrom="30" xTo="300" duration="1000" /> <mx:Fade alphaFrom="1" alphaTo="0" duration="1000" /> </mx:Parallel> <mx:Sequence id="moveAndFadeSequence"> <mx:Move xFrom="30" xTo="300" duration="1000" /> <mx:Fade alphaFrom="1" alphaTo="0" duration="1000" /> </mx:Sequence> <mx:Button id="sendButton" label="Send Email"

mouseDownEffect="{moveAndFadeParallel}" /> <mx:Button id="requestButton" label="Request Brochure" mouseDownEffect="{moveAndFadeSequence}" />

Pgina 152 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 2: Add behaviors to the Cafe Townsend seating chart


In this walkthrough, you will perform the following tasks: Add a Glow effect to the container that holds the image to indicate that the seating chart is interactive Add a Zoom effect to the seating chart when the user mouse over the chart Use the creationCompleteEffect and mouseOverEffect triggers to start the behavior

Steps
Apply the Glow effect to the image's container
1. 2. 3. 4. Open the Customize_wt2.mxml file from the src folder at the root of the project. Run the application. You should see a seating chart. In Flex Builder's Source mode, add a Glow component below the Application container. Set the Glow id property to glowChart, its color style to haloOrange, and its duration to 3000 milliseconds. The code should appear as follows.

<mx:Glow id="glowChart" color="haloOrange" duration="3000" /> 5. Locate the VBox container code and add a creationCompleteEffect property that binds to the glowChart instance. The code should appear as follows.

<mx:VBox creationCompleteEffect="{glowChart}"> 6. Run the application. You should see a haloOrange glow appear around the image for 3 seconds as it fades.

Apply the Zoom effect to the Image control


7. 8. Add a Zoom tag below the Glow tag. Set its id property to ZoomChart and its ZoomWidthTo and ZoomHeightTo properties to 2. The code should appear as follows.

<mx:Zoom id="zoomChart" zoomWidthTo="2" zoomHeightTo="2" />

9.

Locate the Image control and add a rollOverEffect property that binds to the ZoomChart instance. The code should appear as follows.

<mx:Image source="assets/seating_chart_green_room.swf" width ="200" rollOverEffect="{zoomChart}" /> 10. Run the application. You should see the chart zoom in when you mouse over it.

Pgina 153 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Applying transitions to view state changes


Reviewing view states View states let you vary the content and appearance of an application, typically in response to a user action You define the base view state of an application, and one or more additional view states that specify modifications to the base view state When you change view states, the Flex Framework performs all the visual changes to the application at the same time, which means that the components appear to jump from one state to the next Use transitions and effects to form a smooth visual switch from one state to another A transition is one or more effects grouped together to play when a view state change occurs A transition is different than a behavior A behavior applies effects to components A transition applies effects to view states when they change You can apply one or more effects to one or more components in a view state, and you are not limited to the same effects when expanding or collapsing a state Conditional transitions are called effect filters and apply different effects to the same target based on the condition (effect filters are outside the scope of this module) You use the Transition class to create a transition The following table defines the properties of the Transition class Transition class property fromState Description A String that specifies the view state that you are changing from when you apply the transition The default value is an asterisk (*) which means any view state A String that specifies the view state that you are changing to when you apply the transition The default value is an asterisk (*) which means any view state The Effect object to play when you apply the transition Typically, this is a composite effect, such as the Parallel or Sequence effect, that contains multiple effects

toState

effect

Implementing transitions Surround one or more Transition property tags with the transitions tag <mx:transitions> <mx:Transition id="myTransition" fromState="state1" toState="state2"> [...] </mx:Transition> <mx:Transition id="myTransition2" fromState="state2" toState="state3"> [...] </mx:Transition> <mx:Transition id="myTransition3" fromState="*" toState="*"> [...] </mx:Transition> </mx:transitions>

Pgina 154 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Place the desired effects defined earlier in the section on Behaviors within the Transition property component use the target property of the effect to declare the one component to be animated use the targets property of the effect to declare multiple components to be animated

<mx:transitions> <mx:Transition id="myTransition2" fromState="state2" toState="state3"> <mx:WipeLeft duration="400" /> </mx:Transition> </mx:transitions>

The Parallel and Sequence components must be used to define multiple effects within the transition Use the target property of the effect instance or the Parallel and Sequence components, if there is only one target

target="{panel1}" Use the targets property of the effect instance or the Parallel and Sequence components, if there is more than one target

targets="{[panel1, panel2, panel3]}" If you constrain the targets for the Parallel and Sequence components, then only those components will be affected To be even more specific, add the targets property to the effect instances as well

<mx:transitions> <mx:Transition id="myTransition" fromState="state1" toState="state2"> <mx:Sequence targets="{[panel1, panel2, panel3]}"> <mx:Move targets="{[panel1, panel2]}" duration="400" /> <mx:Resize duration="400" /> </mx:Sequence> </mx:Transition> <mx:Transition id="myTransition2" fromState="state2" toState="state3"> <mx:WipeLeft duration="400" /> </mx:Transition> <mx:Transition id="myTransition3" fromState="*" toState="*"> <mx:Parallel targets="{[panel1, panel2, panel3]}"> <mx:Iris duration="400" /> <mx:Move duration="400" /> </mx:Parallel> </mx:Transition> </mx:transitions>

Pgina 155 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Triggering the transitions View state changes are generally triggered by setting the currentState property in the click event of the component trigger When a view state change is triggered, Flex searches for and runs the Transition object that matches the current and destination view specified via the fromState and toState values If more than one transition matches, Flex uses the first definition in the transitions component

Defining the effect start and end values If the effect does not explicitly define the start values of the effect, Flex determines them from the current settings of the component, as defined by the current view state If the effect does not explicitly define the end values of the effect, Flex determines them from the settings of the component in the destination view state If there are no explicit values, and Flex cannot determine values from the current or destination view states, the effect uses its default property values

Pgina 156 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 3: Resize the contact Cafe Townsend panel during the view states transition
In this walkthrough, you will perform the following tasks: Add a sequence animation to the Contact form's view state transition.

Steps
1. 2. Open the Customize_wt3.mxml file from the src folder at the root of the project. Run the application. You should see a Panel with Cafe Townsend information. Click on the Send an email or request a brochure link to see the forms state.

Add the transition


3. 4. In Source mode, add a transitions tag set after the closing States tag and before the Panel container. Nested within the transitions tag set, add a Transition tag with an id property of contactTransition and a fromState and toState property of value * (meaning any).

Add the sequence


5. Nested within the Transition tag body, add a Sequence tag with the target property bound to the contactCafe Panel. The code should appear as follows

<mx:transitions> <mx:Transition id="contactTransition" fromState="*" toState="*"> <mx:Sequence target="{contactCafe}"> </mx:Sequence > </mx:Transition> </mx:transitions> 6. Nested within the Sequence tag, add a Resize effect tag with widthTo property of 700, heightFrom and heightTo properties of 400 and duration of 2000.

Add the effects


7. Add a second Resize effect tag with widthFrom and widthTo properties set to 700, heightFrom property of 400, heightTo property of 550 and duration of 2000. The code should appear as follows.

Pgina 157 de 274

ADOBE FLEX 3 Developing Rich Client Applications <mx:transitions> <mx:Transition id =" contactTransition " fromState="*" toState="*"> <mx:Sequence target="{contactCafe}"> <mx:Resize widthTo="700" heightFrom="400" heightTo="400" duration="2000" /> <mx:Resize widthFrom="700" widthTo = "700" heightFrom="400" heightTo = "550" duration="2000" /> </mx:Sequence> </mx:Transition> </mx:transitions> 8. Run the application. You should see the Panel container animate to the right and then down when you click on the link button. The scrollbars also appear (and then disappear). Add verticalScrollPolicy and horizontalScrollPolicy properties to the Panel container. Set both values to off.

9.

10. Run the application. You should see same animation but now the scrollbars do not appear.

Pgina 158 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Summary
You can change the look and feel of a Flex application by skinning or styling its components Behaviors are dynamic effects applied to components and are a combination of a trigger paired with an effect Transitions are dynamic effects applied to view state changes Ways to set styles specify them inline using the style property values in the components MXML tag use the setStyle() method in ActionScript use cascading style sheets (CSS) in a Style tag type selectors which apply to all instances of that type class selectors which apply to any instances that specify that selector in the styleName property global selector which applies to all controls Use the source property of the Style tag to import an external CSS file Minimize the use of the setStyle() method since it is a resource-intensive call Multi-word style names can only be hyphenated when used in the Style block Use the camel-case equivalent in ActionScript or MXML Use the themeColor style of the Application container to set all component styles to one of the halo colors Effects can be applied in parallel or in sequence One or more transitions can be applied to view state changes with the effects working in parallel or in sequence Use the target or targets property of the effect to determine which components will have animation applied

Review
1. 2. What is the difference between an effect and a trigger? If you do not declare a fromState or a toState in the Transition component, which states are affected by the animations? What is the benefit of referencing an effect component rather than calling it inline on a component from a trigger? Determine the order of precedence for the following styles: The style defined by a class selector The style defined inline The style defined in a global selector The style defined in a type selector 5. Is an external CSS file referenced in the source attribute of the Style component used at run-time or compile-time? Can the CSS style syntax always be used in Flex? Why should you avoid using the setStyle() method?

3.

4.

6. 7.

Pgina 159 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Lab 2:
Objectives
In this lab, you will perform the following tasks: Add navigation to the fStop application Implement absolute positioning Create a view state in Design mode Create transitions for a view state Create a view state using MXML Format the application and custom components using styles

Part 1: Adding application navigation and a custom component


In this part of the lab, you will perform the following tasks: Implement a ViewStack with a LinkBar for application navigation Use absolute positioning in the fStop.mxml application Add a shopping cart custom component to the application

Steps
Import Lab2 Project
1. 2. Select File > Import > Flex Project. Import project from Archive File. o Browse to: <installDirectory>/adobeTraining/f3rca/ Lab2Project.zip o Click Open o Click Finish Close all unrelated projects. Open the FStop.mxml file from the src folder at the root of the Lab2 project. Run the FStop.mxml application. You should see the fStop application as it appeared at the end of the last lab. Notice how the three custom component content is simply stacked vertically.

3. 4. 5.

Add application navigation


In the FStop.mxml file, add a ViewStack tag set around the three custom components, Home, Contribute and Gallery. 7. Give the ViewStack and of fStopContent and set the resizeToContent property to true. 8. Run the application. You should see the fStop header with only the Home content displayed below it. 9. Between the Application tag and the Image tag in the FStop.mxml file, add a LinkBar tag with the data Provider property bound to the ViewStack tag's id of fStopContent. 10. Set the color attribute of the LinkBa r tag to white (#FFFFFF) and the rollOverColor to a bright blue (#B5D2FA). 11. Run the application. You should see the content change to the corresponding ViewStack member when you click on the links in the LinkBar. Notice the bright blue rollover color on the links. 6.

Pgina 160 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Switch the main application to use absolute positioning


12. 13. 14. 15. 16. In the FStop.mxml file, change the layout property of the Application tag to absolute. Add x and y properties to the LinkBar tag with values of 101 and 5, respectively. Add x and y properties to the Image tag with values of 101 and 30, respectively. Add x and y properties to the ViewStack tag with values of 101 and 118, respectively. Run the application. You should see a new layout with space for the shopping cart on the right below the header.

Create the Shopping Cart page component


17. Create a new MXML component based on the Canvas container in the views directory and name it ShoppingCart.mxml with no width or height attribute defined. 18. Set the color attribute for the Canvas tag to black (#000000). 19. Between the Canvas tags, add an Image tag with an id property set to woman, a source that points to the woman.jpg file in the assets/ f Stop directory. 20. Give the Image tag a y property of 100 pixels. 21. Below the Image tag, add a Panel with the following properties and corresponding values. id: cart layout:absolute width:225 height:90 titletShopping Cart border Alpha: 1 headerColors:[#63769E,#B5D2FA] borderThicknessBottom:0 borderThicknessLeft:0 borderThicknessRight:0 paddingBottom: 10

22. Inside the Panel, add a Label control with text set to You have 0 items in your cart. and x and y properties set to 10 and 8, respectively. 23. Below the Label, add a Button control with an id of expandCollapse, a label of expand details and x and y properties set to 10 and 30, respectively. 24. Be sure your finished Panel appears as follows. <mx:Panel id="cart" layout="absolute" width="225" height="90" title="Shopping Cart" borderAlpha="1" headerColors = "[#63769E, #B5D2FA]" borderThicknessBottom="0" borderThicknessLeft="0" borderThicknessRight="0" paddingBottom="10"> <mx:Label text="You have 0 items in your cart." x="10" y="8"/> <mx:Button id="expandCollapse" label="expand details" x="10" y="30"/> </mx:Panel>

Pgina 161 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Call the Shopping Cart component from the main application


25. Return to the FStop.mxml file. 26. Below the Image and above the ViewStack tag, instantiate the Shopping Cart component. 27. Set the x and y positions for the ShoppingCart component to 626 and 118, respectively. The code should appear as follows. <v:ShoppingCart x="626" y="118"/>

28. Run the application. You should see the ShoppingCart component content on the right of the screen, below the header.

Figure 1: fStop application Shopping Cart component content

Part 2: Creating a view state in Design mode and a transition


In this part of the lab, you will perform the following tasks: Create a view state in Design mode to display and hide the shopping cart Use a transition to alter the view states expanding and collapsing

Steps
Expand the shopping cart details
1. 2. Return to the ShoppingCart.mxml file and switch to Design mode. From the Design area dropdown list, select Fit to content to see the entire component content.

Figure 2: Fit to content in Design mode

Pgina 162 de 274

ADOBE FLEX 3 Developing Rich Client Applications

3. 4.

In the Flex Properties view, be sure you are in Standard View. Select the expand details button, and then in the On click field of the Common section of the Flex Properties view set the currentState value equal to expandedCart.

Figure 3: Set the currentState on button click.

5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15.

In the States view, right-click on the <Base state> and select New State... Name the new state expandedCart and click OK. Select the Shopping Cart panel and change its height to 472. This will cover the image of the woman. From the Components view, drag a DataGrid control to the Panel Container below the expand details button and give it a height of 340 and an x and y value of 10 and 60, respectively. Switch to Source mode and remove the last DataGridColumn tag for Column 3 within the DataGrid tag. Return to Design mode. Drag a Button control to below the DataGrid and label it delete with a x and y properties of 10 and 410, respectively. Drag another Button next to the delete button and label it check out with x and y properties of 131 and 410, respectively. Change the expand details button label to collapse details. In the On click field of the Common section of the Flex Properties, update the currentState value equal to . Run the fStop application. You should see the Shopping Cart panel expand and collapse as you click the expand/collapse button.

Figure 4: Expanded Shopping Cart

Pgina 163 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Add a transition to the Shopping Cart state change


16. In Source mode of the ShoppingCart.mxml file, locate the end of the states tag above the Image tag and add a <mx:transitions> tag. 17. Between the transitions tags, add a <mx:Transition > with an id of expandingCart. 18. Set the fromState to an empty value and the toState to the expandedCart state. 19. Between the Transition tags, add a Resize effect with a target bound to the cart instance name of the Panel tag. Note: The default duration is 500 milliseconds. 20. Check to be sure your code appears as follows. <mx:transitions> <mx:Transition id="expandingCart" fromState="" toState="expandedCart"> <mx:Resize target={cart}"/> </mx:Transition> </mx:transitions> 21. Add a second Transition with an id of collapsingCart. 22. Set the fromState to expandedCart and the toState to an empty value. 23. Between the Transition tag, add a Resize effect with a target bound to the cart instance name of the Panel tag, and a duration of 1000. <mx:Transition id ="collapseCart" fromState="expandedCart" toState=""> <mx:Resize target="{cart}" duration="1000"/> </mx:Transition>

24. Run the fStop application. You should see a nice, smooth transition between the two Shopping Cart states as you click the expand / collapse button.

Part 3: Creating a view state in MXML


In this part of the lab, you will perform the following tasks: Create a view state using MXML to create a large image display in the Gallery component

Steps
Create the Gallery large image display
1. 2. 3. 4. Open the Gallery.mxml file in Source mode. At the top of the page, below the opening VBox tag, add a states tag block. Between the states tag, add a State block with a name of details. Between the State tags, add a RemoveChild tag with a target bound to the thumbnailsTile.

<mx:RemoveChild target ="{thumbnails)"/>

Pgina 164 de 274

ADOBE FLEX 3 Developing Rich Client Applications 5. 6. 7. 8. Below the RemoveChild tag, add an AddChild block with a position property set to laStChild. Open the lab2_typing_help.txt file in the views directory and copy all of its content. Paste the Canvas and all of its content between the opening and closing AddChild tags. Review the code and note that the last Button in the Canvas container has a click event already set. Remember that all the Image controls in the Tile thumbnail have their click events already set to the details view. Run the fStop application and go to the Gallery page. You should see the details view appear when you click on any of the thumbnail images in the Tile container. At this point no matter which image you click on you will see the same image in the detail view. Notice the spacing between the elements on the screen.

9.

Figure5: Gallery details

Part 4: Changing the look of the fStop application


In this part of the lab, you will perform the following tasks: Alter the spacing of the fStop application using Styles Alter the look of the fStop application using CSS

Steps
Add formatting for the Home and Contribute content
1. 2. 3. Open the Home.mxml file and add a verticalGap property to the components main VBox tag with a value of 8 pixels. Open the Contribute.mxml file and add a verticalGap property to the component's main VBox tag with a value of 8 pixels. Run the application. You should see minor changes in the spacing between the images on the Home and Contribute content. The spacing is now equal to the spacing between the header and the content areas. Notice the spacing around the text above the Tile container and around the Tile children.

Add formatting for the Gallery content


4. 5. Open the Gallery.mxml file and add a verticalGap property to the component's main VBox tag with a value of 8 pixels. Locate the HBox in the code and set the four padding options as below:

Pgina 165 de 274

ADOBE FLEX 3 Developing Rich Client Applications 6. 7.

paddingBottom:3 paddingLeft:5 paddingRight:5 paddingTop:8

Set the verticalGap property of the Tile container to 15 pixels, the horizontalGap to 20 pixels, and the paddingLeft value to 25 pixels. Run the application. You should see an improvement in the layout of the Gallery content. Notice that all the text fields in the application, except on the Home content, are black. Click on the dropdown in the Gallery and note the light blue colors associated with selecting the values.

Add formatting for the entire fStop application


8. Open the FStop..mxml file and add a Style block below the opening Application container tag. 9. Add a global selector to change the Color of all the text fields to a dark blue (#63769E). 10. Add the default windowStyles class selector for the Panel container and set its header color to dark blue (#63769E). Remember the Panel container has a style named titleStyleName, which by default points to a CSS style named windowStyles. 11. For the ComboBox tag selector, change the fontWeight to normal, the selection-color to dark blue (#63759E) and the roll-over-color to light blue (#B5D2FA). 12. For the Button tag selector, change the fontWeight to normal. The final code should appear as follows. <mx:Style> global { color: #63769E; } .windowStyles { color: #63769E; } ComboBox { fontWeight: normal; selectioncolor: #63769E; roll-overcolor: #B5D2FA; } Button { fontWeight: normal; } </mx:Style>

13. Run the application. You should see that all the text fields except the Home content now have blue text. The Shopping Cart title bar is also blue and the Button controls are no longer bolded.

Pgina 166 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Using ActionScript Data Models


In this unit, you focus on building effective client side data models using both the <mx:Model> tag and ActionScript classes

Objectives
After completing this unit, you should be able to: Use Flex data model with the Model View Controller pattern Create a Flex data model with an MXML tag Create a Flex data model and ActionScript class Use data biding with a data model Use constructor function in a ActionScript class

Topics
In this unit, you will learn about the following topics: Using the MVC design pattern Creating an MXML data model Using ActionScript classes as a data model Creating an ActionScript constructor with parameters Defining class methods

Pgina 167 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Using the MVC design pattern


Flex data modeling is based on the Model-View-Controller (MVC) design pattern which allows for successfully and efficiently relating the user interface to underlying data models

MVC elements
Elements of MVC include Model, which manages data elements and responds to queries about its state and to instructions to change its state View, which manages a rectangular area of the display and is responsible for presenting the data Controller, which handles events from the user and system that affect the model and view These application components allow the separation of the following User interaction Modeling of the external world (data) Visual feedback to the user

Benefits of MVC
Benefits of using MVC designed applications include Better reusability Better maintainability Scalability Proven methodology

Lab application example


The fStop lab application is being built using MVC architecture

Figure 1: fStop MVC architecture

Pgina 168 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Creating an MXML data model


Flex data model stores its data in client side objects A data model is an ActionScript object that contains properties and methods Two types of data models MXML data model For simple models needing no custom methods ActionScript data model For more complex models or models requiring methods

Creating MXML data models


Use the <mx:Model> tag to declare an MXML data model Declare properties as child tags MXML model compiled into a generic ActionScript object Contains untyped properties Names match names of child tags When defining data with subtags, must use a root node Code example <mx:Model id="myEmployee"> <employee> <name> <first>Will</first> <last>Tuckerman</last> </name> <department>Accounting</department> <email>wtuckerman@wilsoncompany.com</email> </employee> </mx:Model> Can use Bindings to access the models data {myEmployee.name.first} {myEmployee.name.last} {myEmployee.department} {myEmployee.email} Note: It is a best practice to always bind to an ArrayCollection, not directly to a Model. Note: When using the data, you do not use the root node. Example MXML tag <mx:Label text="{myEmployee.name.last}"/>

Pgina 169 de 274

ADOBE FLEX 3 Developing Rich Client Applications You can also use bindings to assign the models data <mx:Model id="myEmployee"> <employee> <name> <first>{fname.text}</first> <last>{lname.text}</last> </name> <department> {dep.selectedItem.id} </department> <email>{email.text}</email> </employee> </mx:Model>

Using ActionScript classes as a data model


Creating classes is dependent upon both the class itself and where you store the file that contains the class, called a package

Classpaths and packages


A classpath is where the compiler looks for class files when compiling an application; by default, Flex will look in the same folder as where the MXML file with the Application container is located You can specify custom class paths by right clicking on the project and choosing Properties > Flex Build Path

Figure 2: Setting a custom class path

A package is a group of related classes in one folder under a class path. Use the package keyword to state the path from the class path to the class Separate nested folders with a period

Pgina 170 de 274

ADOBE FLEX 3 Developing Rich Client Applications Code example package food.maindish { public class Pasta { } }

Figure 3: A directory structure

Note: The Flex Builder project name is supplies, so it is not included in the class path

Creating class files


Can include multiple classes in one source file, but only one class in each file can be made available to code that is external to that file Only one class in each file can be declared public Name of the class declared public must match the name of the source file Any additional class definitions in the source file must be declared internal and placed outside the package definition ending brace Code example: File named Pasta.as in the food.maindish package package food.maindish { public class Pasta { } } Instantiate class from MXML file or another AS file Code example Instantiating using MXML <vo:Pasta id="ziti"/> o Instantiating using ActionScript private var ziti:Pasta = new Pasta();

ActionScript classes will often be used to create value objects o Value objects are classes created free of implementation detail and business logic o Contain only value of data related to an object o Often used for transfer of data to a backend o Formally defined in the Core J2EE Pattern catalogue http://java.sun.com/j2ee/patterns/ValueObject.html

Pgina 171 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Also called a transfer object or data transfer object

When creating classes, the follow access modifiers are available o dynamic: Allow properties to be added to instances at run time o final: Can not be extended by another class o internal (default): Visible to references inside the current package o public: Visible to references everywhere o private: Visible to references of the same class

Using the classes


Use fully qualified class name anywhere you reference the class Code example private var ziti:food.maindish.Pasta = new food.maindish.Pasta(); Easier to use import keyword to reference classes Use simple class name anywhere after using import keyword Code example import food.maindish.Pasta; private var ziti:Pasta = new Pasta(); Benefits o Much less typing o Clearly defined at top of file all classes referenced Use * in import statement to represent all classes in a directory o Does not import classes in any subdirectories Note: The use of the * is not recommended for readability concerns. As a style issue it is recommended you list all classes used. Code example, food.maindish package contains classes Pasta and Chicken import food.maindish.*; private var ziti:Pasta=new Pasta(); private var divan:Chicken=new Chicken();

Creating class constructors


Class constructor: a function automatically invoked when instance of a class is created Create by defining a function with same name as the class Code example package food.maindish { public class Pasta { public function Pasta() { } } }

Pgina 172 de 274

ADOBE FLEX 3 Developing Rich Client Applications Constructor not required - compiler will create empty one o Best practice to create an empty constructor Cannot specify a return type Should be declared public

Defining class properties


Be sure to type variables Can assign default values package food.maindish { public class Pasta { public var cookingTime:int=20; public var cost:Number; ... Possible attributes when declaring properties o o o o o internal (default): Visible to references inside the same package private: Visible to references in the same class protected: Visible to references in the same class and derived classes public: Visible to references everywhere static: Specifies that a property belongs to the class, as opposed to instances of the class

Instantiating ActionScript classes in MXML


When you instantiate a class in MXML using a tag, you cannot pass data to a constructor You can only set values for optional public properties Instance will still be created even though parameters not sent to constructor

Making properties bindable


Data binding is the process of binding the data of one object to another object If properties of ActionScript classes are going to be used in data bindings need to be declared as such in the class definition Two possible ways to declare properties bindable o If all properties will be used in bindings, make the class bindable package valueObjects { [Bindable] public class RestaurantProduct { public var idNo:int; public var prodName:String; public var description:String; public function } } }

Pgina 173 de 274

ADOBE FLEX 3 Developing Rich Client Applications RestaurantProduct() {

} } }

Pgina 174 de 274

ADOBE FLEX 3 Developing Rich Client Applications

If only a few of the properties will be used in bindings, make only those bindable

package valueObjects { public class RestaurantProduct { [Bindable] public var idNo:int; public var prodName:String; [Bindable] public var description:String; public function RestaurantProduct() { } } }

Pgina 174 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 1: Instantiating an Object in MXML from an ActionScript class


In this walkthrough, you will perform the following tasks: Build a class in ActionScript Instantiate the class in MXML

Steps
Import DataModel Project
1. 2. Select File > Import > Flex Project. Import project from Archive File. o Browse to: <installDirectory>/adobeTraining/f3rca/ DataModelProject.zip o Click Open o Click Finish Close all unrelated projects.

3.

Create an ActionScript Class


4. Select File > New > ActionScript Class. o Package: valueObjects o Name: RestaurantProduct o Uncheck: Generate constructor from superclass o Keep all other defaults Click Finish to create the file.

5.

Figure 4: Creating the RestaurantProduct class

Pgina 175 de 274

ADOBE FLEX 3 Developing Rich Client Applications

6.

Under the opening brace for the class, create three publiC variables the following names and data types: idNo:int prodName:String description:String

7.

Create a public constructor for the class. In this case, the constructor empty:

public function RestaurantProduct() { } 8. Be sure your class appears as follows and save the file.

package value Object { public class RestaurantProduct { public var idNo: int; public var prodName: String; public var description:String; public function RestaurantProduct( ) { } } }

Instantiating the RestaurantProduct class


9. Open the DataModel_wt1.mxml file in the src folder at the root of the project. 10. Add an XML namespace in the <mx:Application> tag named vo which allows access to the classes in the valueObjects directory. xmlns:vo="valueObjects.*" 11. Create an object, with an MXML tag, of the RestaurantProduct class with an id of garlic. Don't forget to use vo as the prefix. Supply the following values for the public properties. idNo: 1 prodName: Gallon of Garlic description: Industrial strength <vo:RestaurantProduct id ="garlic" idNo ="1" prodName="Gallon of Garlic" description="industrial strength"/> 12. Create three Labels to display the properties of the new object. <mx:Label <mx:Label <mx:Label text ="{garlic.idNo}" /> text ="{garlic.prodName}" /> text ="{garlic.description}"/>

13. Run the application. You should see the three property values displayed in the Label controls.

Pgina 176 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Correcting the data bindings warnings


14. In the Problems view, note three warnings, one of which is shown here. Data binding will not be able to detect assignments to "idNo". 15. To fix this situation, return toResraurantProduct.as. Since all the properties will be used in bindings, mark the entire class bindable. package valueObjects { [Bindable] public class Restaurant Product { public var idNo:int ; public var prodName: String; public var description: String; public function Restaurant Product { } } } 16. Save the ActionScript class and note that the warnings disappear. 17. Return to DataModel_wt1.mxml and run the application. You should see the application behaves just as it did before.

Creating an ActionScript constructor with parameters


ActionScript classes can be created with constructors that use parameters o Parameters are used to pass data to the constructor Parameters are never used when instantiating from MXML, only from ActionScript If parameter names are the same as property names, you will have to refer to the instance itself when assigning parameter values to instance properties o Use the this keyword If the constructor method uses required parameters without default values, that class cannot be instantiated in MXML o There is no way to pass parameters to the constructor in MXML

Clarifying the use of the this keyword


In an application file, this refers to the application itself

Figure 5: The this keyword refers to the application

Pgina 177 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Note: You cannot give the application an instance name, so you must refer to it as this. In a custom MXML component file, this refers to the custom component itself

Figure 6: The this keyword refers to the DataGrid

You cannot give the custom component an instance name, so you must refer to it as this In an ActionScript class, this refers to the class itself

Figure 7: The this keyword refers to the class

Using constructor parameters


Parameters accepted as a comma separated, datatyped list in parentheses after the constructor name Use the parameter value in the constructor by its name

Figure 8: Using parameters

Code example ziti:Pasta = new Pasta(23,1.02);

Pgina 178 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 2: Instantiating an Object in ActionScript from an ActionScript class


In this walkthrough, you will perform the following tasks: Instantiate an object from an ActionScript class in an <mx:Script> block

Steps
1. Open RestaurantProduct2.as in the valueObjects folder.

Adding arguments to the class


2. In the parentheses for the constructor, add in the following three arguments, datatyped as shown: o idNo:int o prodName:String o description:String In the constructor, assign the instance variable idNo the value of the corresponding parameter:

3.

this.idNo=idNo; 4. 5. Assign the prodName and description instance variables their corresponding values. Be sure your complete class appears as follows.

package valueObjects { [Bindable] public class RestaurantProduct2 { public var idNo:int; public var prodName:String; public var description:String; public function RestaurantProduct2(idNo:int prodName:String,description:String) { this.idNo=idNo; this.prodName=prodName; this.Description=description; } } } 6. Save the file.

Instantiating the object in ActionScript


7. 8. Open the DataModel_wt2.mxml file in the src folder at the root of the project. Insert a Script block.

Pgina 179 de 274

ADOBE FLEX 3 Developing Rich Client Applications

9.

So you don't have to use the complete class path in instantiation, import the RestaurantProduct2 class from the valueObjects directory:

import valueObjects.RestaurantProduct2; 10. After the import statement in the Script block, create a private Bindable RestaurantProduct2 object named tabasco, datatyped as RestaurantProduct2. 11. Pass the following parameters to ReStaurantProduct2 o 2 o Tabasco Sauce o Designed for the restaurant industry 12. The final code in the <mx:Script> block should look as follows:

<mx:Script> <![CDATA[ import valueObjects.RestaurantProduct2; [Bindable] private var tabasco:RestaurantProduct2 = new RestaurantProduct2(2, "Tabasco Sauce", "Designed for the restaurant industry"); ]]> </mx:Script> 13. Uncomment the Label controls. 14. Run the application. You should see that the Label controls are populated with the text.

Pgina 180 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Defining class methods


Defined inside the class Specify one of the following access modifiers o public - methods accessible from anywhere o private - methods can only be called from within the class o protected - methods can be called from within class or subclass o internal - methods can be called from other classes in the same package o Code example

package food.maindish { public class Pasta { public function Pasta() { } public function alDente():int { return 13; } } }

Invoking a method
To invoke a method of the class o Instantiate the object o Invoke the method Code example <mx:Script> <![CDATA[ import food.maindish.Pasta; [Bindable] public var gnocchi:Pasta=new Pasta(); ]]> </mx:Script> <mx:Label text="Cook time for al dente: {gnocchi.alDente()}"/>

Pgina 181 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Defining static methods


Creates a method that can be accessed without instantiating an object of that particular class o Can save memory o Can specify before or after public/private/internal/protected o Code example static public function getRestName():String { return "Cafe Townsend"; }

Invoking a static method


Do not have to instantiate an object of the class before using the method Code example <mx:Script> <![CDATA[ import food.maindish.Pasta; ]]> </mx:Script> <mx:Label text="{Pasta.getRestName()}"/>

Pgina 182 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 3: Adding Methods to an ActionScript class


In this walkthrough, you will perform the following tasks: Add a normal and static method to an ActionScript class Invoke these methods from MXML

Steps
1. Open RestaurantProduct3.as in the ValueObjects folder.

Adding a method
2. Add a public function with the name of prodInfo, datatyped as String, that returns the prodName and description separated by a colon and space.

public function prodInfo():String { return this.prodName+": "+this.description; } 3. Save the file.

Invoking the method


4. 5. Open the DataModel_wt3.mxml file in the src folder at the root of the Where indicated by the comment, use a Label control to display the string returned by the method invocation.

<mx:Label text="{garlic.prodInfo()}"/> 6. Run the application. You should see the product name and description displayed in the Label.

Adding a static method


7. 8. Return to RestaurantProduct3.as. After the existing method, add a Static public function named getRestName, datatyped as String, that returns the text Cafe Townsend.

static public function getRestName():String { return "Cafe Townsend"; } 9. Return to DataModel wt3.mxml. 10. Below the existing Label control, add another Label control. 11. In the new Label's text property, invoke the static method getRestName() directly from the class RestaurantProduct3

Pgina 183 de 274

ADOBE FLEX 3 Developing Rich Client Applications

<mx:Label Text="{RestaurantProduct3.getRestName()}"/> 12. Run the application. You should see the words Cafe Townsend in the second Label.

Summary
In Flex applications you can easily separate the display from processing using an MVC design pattern To create a data model use either the <mx:Model> tag or an ActionScript class In ActionScript, you can create classes and reference packages You can define instance and static class properties You can use public, private, protected and internal to control access to class members Create a class constructor that is called when class instances are created To use data models with data binding, use the Bindable metatag

Review
1. 2. 3. 4. 5. Name two design patterns that you worked with in this unit. Describe some limitations of the Model tag. Name and describe the use of all the different access modifiers to control access to class members. What does the this keyword refer to? What are the benefits of using static methods?

Pgina 184 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Exchanging Data Between Components Using Custom Events


In this unit, you will learn how to create a custom Event object, set the metadata and dispatch the custom event to pass data between loosely-coupled components.

Objectives
After completing this unit, you should be able to: Understand the issues of using bindings to get data from components Understand the benefits of a loosely coupled architecture Create custom events Dispatch custom events Identify the need for custom event classes Inherit from the Event base class to create a custom event subclass Understand the event flow

Topics
In this unit, you will learn about the following topics: Understanding the problem with bindings Creating custom events Sending data with a custom event

Pgina 185 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Understanding the problem with bindings


There are issues in using bindings to get data from components There are advantages to using loosely coupled components

The problem of using bindings


Up to now, you have used bindings to obtain data from a component by binding to a particular property of the component o Need to be invasive into a component to know the inner details o If the code in that component changes, reliant code will break (such as a changed ID for an object) An example of this is depicted below

Figure 1: Reaching into a component to retrieve data

A much cleaner approach would be to let the component dispatch an event, just like a Button dispatches a click event

Creating loosely coupled components


Components should be created as black boxes o They do not have direct knowledge of any other components inner workings o Data they require is sent in through binding variables to component public properties o Data is to be returned in this same manner Enables easier reusability and maintenance of components Best practice is for components to dispatch events with data that the application can listen for and handle

Pgina 186 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Demonstration 1: Using a binding to get data from a component


In this demonstration, your instructor will perform the following tasks: Look at an application where a menu item can be selected Walk through the application code and demonstrate that the method used is a bad practice because it creates dependent components

Steps
Import the CustomEvents Project
1. 2. Select File > Import > Flex Project. Import project from Archive File. o Browse to: <installDirectory>/adobeTraining/f3rca/ CustomEventsProject.zip o Click Open o Click Finish Close all unrelated projects. Open the CustomEvents_demo1.mxml file from the src folder at the root of the CustomEvents project. Run the application. You should see a simple application where you can choose from four menus. When you select a menu, the chosen item is shown on the screen.

3. 4. 5.

Looking at the code


6. 7. 8. 9. Return to Flex Builder and open ChooseMenu_demo1.mxml file from the src folder. Notice that there are no events nor event handlers in the component that extends VBox. Switch to CustomEvents_demo1.mxml. View the following code.

<comp:DisplayMenu menuForDisplay="{menuChooser.menuGroup.selection.label}"/> Note: Note that this application "reaches" into the menuChooser object top the label of the selected RadioButton. This is not a best practice.

Creating custom events


Five steps to create a custom event 1. 2. 3. 4. 5. Define the custom event with Flex using the [Event] MetaData tag Instantiate the Event Dispatch the event Create an event handler to handle the event Use the data

Pgina 187 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Figure 2: Dispatching and handling a custom event

Defining the event


A component needs to define every event it may dispatch Subclasses can dispatch events inherited from their super classes With the definition of an event, a name and an event object are specified In the following code block o The name attribute specifies the name of the event o The type attribute specifies the class that defines the event When the default Event base class is used, the type attribute can be omitted When a custom event object is used, it must be a subclass of the flash.events.Event class <mx:Metadata> [Event(name="eventName", type=flash.events.Event)] </mx:Metadata>

Creating an event object


Create an instance of an event object that will eventually be dispatched var event:Event = new Event("eventName");

Dispatch the event


You dispatch an event using the dispatchEvent() method whose signature is as follows: object.dispatchEvent(event:Event):Boolean The required parameter must be or inherit from Event Any event, including custom events can be dispatched using dispatchEvent()

Pgina 188 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Example
<?xml version="1.0" encoding="utf-8"?> <mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:Metadata> [Event(name="myCustomEvent", type="flash.events.Event")] </mx:Metadata> <mx:Script> <![CDATA[ private function clickHandler():void { var eventObj:Event = new Event("myCustomEvent"); dispatchEvent(eventObj); } ]]> </mx:Script> <mx:Button click="clickHandler()" /> </mx:VBox>

Implement an event handler to handle the event


Events dispatched from custom event classes are handled in the same manner as build-in Flex events o Handle that event just like other Flex components In the code below, the Buttons click event is handled by calling the clickHandler() event handler <mx:Button click="clickHandler()"/> In the code below, the myCustomComponent event of the MyComponent custom component will be handled by the customEventHandler() event handler function o Syntax just the same as used by a built-in component handling a built-in event <local:MyComponent myCustomEvent="customEventHandler()"/>

Complete example of custom event handling


<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/ 2006/mxml"> <mx:Script> <![CDATA[ private function customEventHandler():void { theLabel.text="button inside custom component is clicked"; }

Pgina 189 de 274

ADOBE FLEX 3 Developing Rich Client Applications ]]> </mx:Script> <local:MyComponent myCustomEvent="customEventHandler()"/> <mx:Label id="theLabel"/> </mx:Application>

Walkthrough 1 : Creating, dispatching and handling a custom event


In this walkthrough, you will perform the following tasks: Create a custom event to be dispatched from the ChooseMenu component Dispatch the custom event when a menu item is selected Create an event handler in the CustomEvents application and register it to handle the custom event Populate a property on the custom event class with text Pass the property to another custom component by dispatching its containing Event

Figure 3: Custom event workflow in the walkthrough

Pgina 190 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Steps
Import the CustomEvent Project
1. 2. If the CustomEvent project is not already imported, select File > Import > Flex Project. Import project from Archive File. o Browse to: <installDirectory>/adobeTraining/f3rca/ CustomEventProject.zip o Click Open o Click Finish Close all unrelated projects.

3.

Creating a custom event


4. 5. Open the CustEvDispatcher_wt1.mxml from the src folder at the root of the project. At the top of the component, above the Script block, define a custom event, using Metadata. Use custEvName as the name for the custom event, and use the flash.events.Event base class for the type:

<mx:Metadata> [Event(name="custEvName", type="flash.events.Event")] </mx:Metadata>

Instantiate and Dispatch the custom event when a menu item is selected
6. In the RadioButtonGroup component, add an itemClick event. Name the event handler clickHandler.

<mx:RadioButtonGroup id="menuGroup" itemClick ="clickHandler()"/> Inside the Script block, create a private function named clickHandler(), returning void. 8. In the function, create a local variable named eventObj, datatyped as Event, and set it equal to a new Event object. Pass the string, custEvName, as a parameter to the Events constructor. 9. Dispatch the custom event, using the dispatchEvent() method sending the event object, eventObj as a parameter. 10. Check to be sure your function appears as follows. 7. private function clickHandler():void { var eventObj:Event=new Event("custEvName"); dispatchEvent(eventObj); }

Pgina 191 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Create an event handler for the custom event


11. Open the CustEvMainApp_wt1.mxml from the src folder at the root of the project. 12. Inspect the code. It has two custom components and one private property. 13. In the instantiation of the CustEvDispatcher component, use code hinting (available because of the Event MetaData tag) to add the custom event custEvName. 14. In the ActionScript associated with the custEvName event, specify the custEvNameHandler() function. 15. Implement the event handler for the custom event inside the Script block by creating & private function, named custEvNameHandler(), returning void. 16. Inside the function, populate the selectedMenu property with the string value, A menu is selected. Note that this variable is bound to the MenuForDisplay attribute of the DisplayMenu component. 17. Make sure your code appears as follows. <mx:Script> <![CDATA[ [Bindable] private var selectedMenu:String; private function custEvNameHandler():void { selectedMenu ="A menu is selected"; } ]]> </mx:Script> <comp:CustEvDispatcher_wt1 id="menuChooser" custEvName="custEvNameHandler()"/> <comp:DisplayMenu menuForDisplay="{selectedMenu}"/>

18. Open the DisplayMenu component to see its inner workings. This component only displays the value of the menuForDisplay property. 19. Run the CustEvMainApp_wt1.mxml application. You should see the working application. When you select a menu item the text "A menu is selected" should be shown. This text does not change with different selections. We have now created a loosely coupled component. The only problem is that we need the selected choice to be sent out with the custom event.

Pgina 192 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Sending data with a custom event


Often you want to send data with the custom event This is done by creating custom event classes that contain properties to hold the data

Identifying the need for a custom event class


So far we have used the custom event as a notifier that something happened in the component that others are interested in Sometimes you need to send data between components using the custom event o For example, the CustomEventClass needs to send the name of the selected menu item as part of the custom event The flash.events.Event base class does not support adding properties to it Therefore, you need to extend the Event class so you can add properties to a new event class

Creating a custom event class


When you create a custom event class, it will extend the flash.events.Event base class package events { import flash.events.Event; public class CustomEventClass extends Event { } }

Adding properties
You can now add properties to hold the data that you want to send with the custom event public var custEvProperty:String;

Creating the constructor


The constructor should do at least 2 things o Call super() The constructor of the Event Class is defined to take the type as an argument, so you can pass the type property directly to the super class to set it o Populate the properties you added Your properties can be of any built-in types such as Strings, Numbers, etc. Can also be typed as a custom class

Pgina 193 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Constructor arguments
The constructor takes two arguments o The data you want to pass with the custom event o The type public function CustomEventClass( type:String, custEvPropertyParameter:String) super(type) this.custEvProperty=custEvPropertyParameter; } Note: The this prefix is not required; It would be if the parameter name matched the class property name, which is often the case.

Overriding the clone method


Override the clone() method of the super class o clone() method returns a new instance of your custom event class o Required to support event bubbling override public function clone():Event { return new CustomEventClass(type, custEvProperty); }

Using the custom event class


To use the custom event class o Define the custom event using Metadata compiler directive o Instantiate and dispatch the custom event

Define using Metadata


In the Metadata section, you define the event you plan to dispatch o Use the name argument to specify the name of the custom event o Use the type argument to specify the class that defines the event The type will refer to a custom event ActionScript class <mx:Metadata> [Event(name="custEvName", type="events.CustomEventClass")] </mx:Metadata>

Pgina 194 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Dispatch the custom event


To dispatch the custom event within an event handler 1. 2. 3. 4. Import the custom event class Create an instance of your custom event class using the new operator Populate the properties of the new custom event object Send it into the Flex event flow using the dispatched event

Example
import events.CustomEventClass; private function clickHandler():void { var eventObj:CustomEventClass = new CustomEventClass("custEvName",customPropertyValue); dispatchEvent(eventObj); } where o CustomEventClass is the class name of the custom event that you created in ActionScript. custEvName is the custom event name defined in the Metadata tag. customPropertyValue is the value you want to use to populate your custom property

Handling the custom event


In MXML, add the custom event keyword as a parameter to the control where the custom event was defined Pass the event object to the event handler custEvName="custEvNameHandler(event)" In ActionScript, import the custom event class in the Script block Handle the custom event within the event handler import events.CustomEventClass private function custEvNameHandler( event:CustomEventClass):void { [handle event] }

Pgina 195 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 2: Creating a custom event object and dispatching it


In this walkthrough, you will perform the following tasks: Create a custom event ActionScript class Populate a property of the custom event object Dispatch the event with the data Extract the data from the events custom property to use

Steps
Creating a custom event object class
1. 2. Right-click on the events folder in the src folder and select New > ActionScript class. In the New ActionScript Class dialog box supply the following values. o Package: events o Name: CustomEventClass o Modifiers: public o Superclass: flash.events.Event (If you use the Open Type dialog be patient, it takes a bit of time to list all the classes) 3. 4. Click Finish. Just below the class definition, create a public property to hold the chosen menu. Name it custEvProperty, datatyped as String.

public var custEvProperty:String; 5. Below the property declaration, create a constructor with the name of CustomEventClass. Accept the following two parameters with the indicated dataype: o o type: String custEvPropertyParameter: String

Note: Remember the constructor function cannot be datatyped. 6. 7. Inside the constructor, call the super() method, passing the type parameter as an argument. Assign the property you created in step 4, referenced as this.custEvProperty, with the value of the customEvPropertyParameter parameter. Create another public function that overrides the parent class clone method, and returns Event. In the function, return a new instance of the CustomEventClass custom event object, passing type and custEvProperty as parameters.

8. 9.

10. The Class should appear as follows

Pgina 196 de 274

ADOBE FLEX 3 Developing Rich Client Applications package events { import flash.events.Event; public class CustomEventClass extends Event { public var custEvProperty:String; public function CustomEventClass (type:String,custEvPropertyParameter:String) { super(type); this.custEvProperty=custEvPropertyParameter; } override public function clone():Event { return new CustomEventClass(type,custEvProperty); } } }

Send the property data with the custom event


11. Open CustEvDispatcher_wt2.mxml from the src folder at the root of the project. 12. Import the events.CustomEventClass class. 13. Change the event definition so that it is datatyped as the new custom event class. <mx:Metadata> [Event(name ="custEvName", type="events.CustomEventClass")] </mx:Metadata> 14. In the clickHandler() function, change the datatype of the eventObj variable from the base class Event to the custom event CustomEventClass. 15. Set the eventObj variable equal to an instantiation of the CustomEventClass class, passing the string custEvName and label of the selected RadioButton as parameters. var eventObj:CustomEventClass = new CustomEventClass ("custEvName",menuGroup.selection.label); 16. Your code should appear as follows. <mx:Metadata> [Event(name="custEvName", type="events.CustomEventClass")] </mx:Metadata> <mx:Script> <![CDATA[ import events.CustomEventClass; private function clickHandler():void { var eventObj:CustomEventClass = new CustomEventClass("custEvName", menuGroup.selection.label); dispatchEvent(eventObj); } ]]>

Pgina 197 de 274

ADOBE FLEX 3 Developing Rich Client Applications </mx:Script>

Pgina 198 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Handling the event and using the new custom event object
17. Open CustEvMainApp_wt2.mxml from the src folder at the root of the project. 18. In the Script block, import the events.CustomEventClass class. Notice how the import statement follows the directory structure to the class file. 19. In the instantiation of the CustEvDispatcher_wt2 class, pass the event object as a parameter in the custEvNameHandler function call. custEvName="custEvNameHandler(event)" 20. Edit the custEvNameHandler function to accept the event object, datatyped as CustomEventClass as the parameter. 21. Populate the selectedMenu variable with the custEvProperty property of the event object. 22. Your code should look like this. <mx:Script> <![CDATA[ import events.CustomEventClass [Bindable] private var selectedMenu:String; private function CustEvNameHandler(event:CustomEventClass):void { selectedMenu = event.custEvProperty ; } ]]> <mx:Script> 23. Run the application. You should see that when you select a menu item, the name of the selected menu item is displayed. The ChooseMenu_wt2 component now functions as a loosely coupled component, dispatching an event when a menu item is selected and sending the selected menu items label property stored in a property of the custom event.

Pgina 199 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Summary
Events help to achieve loose coupling amongst components This can help improve reusability and maintenance for your application Custom events need to be defined, instantiated, dispatched and handled An event is an instance of the flash.events.Event class You can subclass this base class of all Events to add custom properties A custom subclasss constructor should call super()

Review
1. 2. What is the advantage of loosely coupled components? The default Event class in Flex is a. b. c. d. event mx.core. Event flash.events.Event Any class you specify in the event declaration

3.

True or False: dispatchEvent() always sends an event object with the event.

4.

True or False: A custom event object should always extend the default Event class.

5.

A custom event class should: (Choose 2) a. b. c. d. Have 'event' in its classname Can have no custom methods Should override the clone() method Should call super() of its parent

Pgina 200 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Creating Data Entry Forms


In this section of the course, you will learn how to use the Form container to present a data entry form, and how to validate and share the values entered into the form controls by the user.

Objectives
After completing this unit, you should be able to: Lay out data entry forms with the Form container Initialize form controls values with value object properties Validate form controls with Validator classes Share data with the application with custom events and value objects

Topics
In this unit, you will learn about the following topics: Using the Form container Sharing Form Data Validating form data Triggering validation with events Triggering validation with ActionScript

Pgina 200 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Using the Form container


The Form container handles layout and presentation of a data entry form Unlike HTML data entry forms, the Form container does not handle these features o Packaging of data to send to the server o Application navigation The Form container uses FormHeading, FormItem and form controls to layout form content The FormHeading controls displays a large bold label above the Forms right column The FormItem container indicates required fields with asterisks and provides for data validation

Using form components


Forms are often created as MXML custom components that encapsulate form behavior o Collection of data o Sharing of data through dispatching of custom events o Validation of data using Validator classes and ActionScript code The following table describes the types of MXML tags that you use to lay out forms

Tag <mx:Form> <mx:FormHeading>

Description The outermost container that defines the entire form Optional control that defines a heading within your form You can have multiple FormHeading controls within a single Form container that logically group multiple content areas A FormItem container specifies a single label and one or more child components The label is vertically aligned with the first child in the FormItem container A single Form container can hold multiple FormItem containers

<mx:FormItem>

Using the FormItem container


The FormItem container contains one or more controls Each FormItems label property displays a label in the forms left column Labels are right-aligned with each other in the left column FormItem containers required property displays an indicator (a red asterisk) when set to true o Validation is not enforced by the FormItem container By default, multiple nested controls stack vertically within a FormItem container FormItem containers direction property causes nested controls to lay out left to right when set to horizontal Example <mx:FormItem label="State/Zip:" required=true direction=horizontal> <mx:TextInput id="zipInput"/> <mx:TextInput id="stateInput"/> </mx:FormItem>

Pgina 201 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Creating a Form custom component


Create a custom component with <mx:Form> as root element Create as an MXML file in project subfolder Example save as LoginForm.mxml in a forms subfolder of the project source root <?xml version="1.0" encoding="utf-8"?> <mx:Form xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:FormItem label="User:" required=true> <mx:TextInput id="userInput"/> </mx:FormItem> <mx:FormItem label="Password"> <mx:TextInput id="passwordInput"/> </mx:FormItem> <mx:FormItem> <mx:Button label="Log In"/> </mx:FormItem </mx:Form> Use MXML to instantiate the form in the application Example <forms:LoginForm id=myLoginForm/> The resulting Form component looks like the following

Figure 4: Form component in design mode

Pgina 202 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 1 : Creating a data entry form component


In this walkthrough, you will perform the following tasks: Create a Flex form Use the Form container Use the FormHeading control Use the FormItem container

Steps
Import the Forms Project
1. 2. Select File > Import > Flex Project. Import project from Archive File. o Browse to: <installDirectory>/adobeTraining/f3rca/ FormsProject.zip o Click Open o Click Finish Close all unrelated projects.

3.

Create a Form custom component


4. 5. 6. 7. Right-click on the forms subfolder of the src folder in the Forms project and select New > MXML Component. Set the Filename as CalcForm_wt1.mxml. Base the component on the Form container and remove any height or width settings. Click Finish to create the custom component. When the custom component opens in the editor, switch to Source mode if necessary. Your code should look like this.

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

Add form controls to the Form


8. 9. Switch to Design mode. From the Layout section of the Components view, drag a FormHeading component into the Component. 10. Set the label property of the FormHeading component to Tip Calculator. 11. From the Controls section of the Components view, drag a TextInput control into the component. You should see that the TextInput control is automatically wrapped in a FormItem container. 12. Set the TextInput control's id property to amountInput.

Pgina 203 de 274

ADOBE FLEX 3 Developing Rich Client Applications

13. Select the FormItem container that wraps the TextInput control and set its label property to Amount:. 14. Drag another TextInput control into the component below the first one. Set its id property to percentInput. 15. Select the FormItem container that wraps the TextInput control and set its label property to Percent Tip: 16. Drag a Button component into the component. Set its label property to Calculate. 17. Select the FormItem container that wraps the Button control and set its label property to a blank string. 18. Confirm the form looks like the following.

Figure 5: The form component in design mode

19. Switch to Source mode and review the components generated code. The component's source code should look like this. <?xml version="1.0" encoding="utf-8"?> <mx:Form xmlns:mx="httpp://www.adobe.com/2006/mxml"> <mx:FormHeading label="Tip Calculator"/> <mx:FormItem label="Amount:"> <mx:TextInput id="amountInput"/> </mx:FormItem> <mx:FormItem label="Percent Tip:"> <mx:TextInput id="percentInput"/> </mx:FormItem> <mx:FormItem> <mx:Button label="Calculate"/> </mx:FormItem> </mx:Form> 20. Save the component file.

Add the Form component to the application


21. Open Forms_wt1.mxml. 22. Switch to Design mode. 23. From the Custom folder of the Flex Builders Components view, drag the custom CalcForm_wt1 container to the design surface. 24. Run the application. You should see the form presented in the application. 25. Return to Flex Builder and switch to Source mode. You should see that the custom component has been added to the application with MXML and a custom namespace prefix of nsl. <?xml version="1.0" encoding="utf-8"?> <mx;Application xmlns:mx="http ://www.adobe.com/2006/mxml " xmlns:nsl ="forms.*" > <nsl:CalcForm_wt1> </nsl: CalcForm_wt1> </mx:Application>

Pgina 204 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Sharing Form Data


Share data with the application from a Form component using a custom event class and a value object class

Creating a Value Object


Design an ActionScript class as a value object to contain data collected from the form Example package valueObjects { [Bindable] public class CalcData { public var amount:Number; public var percent:Number; public var result:Number; public function CalcData() { } } }

Creating a Custom Event


Design a custom event class to wrap the value object Include a public property typed as the value object class package events { import flash.events.Event; import valueObjects.CalcData; public class CalcEvent extends Event { public var data:CalcData; public function CalcEvent( type:String, data:CalcData) { super(type); this.data = data; } } }

Pgina 205 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Declaring and dispatching the custom event


Declare the custom event with the [Event] metadata tag Example <mx:Metadata> [Event(name="calculate", type="events.CalcEvent")] </mx:Metadata> Instantiate the value object and populate with data from the form Example import events.CalcEvent; import valueObjects.CalcData; private function calculate():void { var formData:CalcData = new CalcData(); formData.amount = Number(amountInput.text); formData.percent = Number(percentInput.text); formData.result = formData.amount * (formData.percent/100); var event:CalcEvent = new CalcEvent( "calculate", formData); dispatchEvent(event); }

Handling the custom event


Handle the event with a custom event handler in the application Extract the data from the event object and save to a bindable variable Example [Bindable] private var myCalcData:CalcData; private function calcHandler( event:CalcEvent):void { myCalcData = event.customProp; }

Pgina 206 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 2: Sharing Form Data with the Application


In this walkthrough, you will perform the following tasks: Review pre-built custom event class and value object class Declare and dispatch a custom event in a custom Form component Handle the event and save the data in the application

Steps
1. 2. 3. 4. Open CalcData.as from the valueObjects folder. Review the value object code. Notice that the result property is calculated within the class using a get accessor method. Since there is no Set method, this is a read-only property. Open CalcEvent.as from the events folder. Review the custom event object code.

Declare the custom event


5. 6. 7. Open the form component CalcForm_wt2.mxml from the forms folder. Add an <mx:Metadata> tag set below the <mx:Form> start tag. Within the <mx:Metadata> tags, add an [Event] metadata tag with the following settings. o name: calculate o type: events. CalcEvent Confirm that the code looks like the following.

8.

<mx:Metadata> [Event (name="calculate", type="events.CalcEvent")] </mx:Metadata>

Instantiate the value object and dispatch the custom event


9. Within the existing calculate() function, declare an instance of the CalcData value object named formData.

var formData:CalcData= new CalcData(); 10. Set the value objects amount and percent properties from their respective form controls, using the form controls, using the Number() Casting function to cast the input controls text properties to numeric values. formData.amount = Number(amountInput.text); formData.percent = Number(percentInput.text);

Pgina 207 de 274

ADOBE FLEX 3 Developing Rich Client Applications 11. Create an instance of the CalcEvent custom event class named event. In the call to the constructor method, pass the event name as calculate and the CustomProp property as the formData object. var event:CalcEvent=new CalcEvent("calculate", formData); 12. Dispatch the event object. dispatchEvent(event); 13. Confirm that the completed calculate( ) function looks like the following. import events.CalcEvent; import valueObjects.CalcData; private function calculate():void { var formData:CalcData = new CalcData(); formData.amount = Number(amountInput.text); formData.percent = Number(percentInput.text); var event:CalcEvent = new CalcEvent("calculate", formData); dispatchEvent(event); }

Handle the event in the application


14. Open Forms_wt2.mxml. 15. Notice that a bindable instance of CalcData has been declared as the variable myCalcData. 16. In the form component instance, <nsl:Calcform_wt2>, add a custom event handler for the calculate event that dispatches the event object to the calcHandler () function. <nsl:CalcForm_wt2 calculate="calcHandler(event)"> </nsl:CalcForm_wt2> 17. In the calcHandler() function, extract the customProp property from the event object and save it to the predeclared myCalcData variable. myCalcData = event.customProp; 18. Run the application. Enter numeric values into the form controls and click the Calculate button. You should see that the returned value objects properties are displayed in the application.

Figure 6: The completed tip calculator application

Pgina 208 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Validating form data


Form validation ensures that data meets specific criteria before the application uses it Flex uses a set of Validator classes which can be used to validate data entered into form controls o Validator class is the base class for all other validator classes These classes are subclassed from Validator class and are designed to validate particular kinds of values o CreditCardValidator o DateValidator o EmailValidator o NumberValidator o PhoneNumberValidator o SocialSecurityValidator o StringValidator o ZipCodeValidator o RegExpValidator

Creating a Validator with MXML


Create one validator class instance for each form control whose value needs to be validated o For instance, consider this TextInput control <mx:TextInput id="phoneInput"/> To validate the value entered in this input control, create an instance of a validator class o Code creates an instance of a PhoneNumberValidator using MXML <mx:PhoneNumberValidator id="phoneV" source="{phoneInput}" property="text"/> The source is entered as a binding expression, and the property as a simple text value Each validator class has these properties

Property source property required

Description The id of the object whose value will be validated The name of the objects property that will be validated A boolean property indicating whether the validated property must have a value An object whose event will be used to trigger validation The name of the event that will trigger validation

trigger triggerEvent

Each Validator subclass has properties that allow you to turn on specific validation rules and set custom error messages

Pgina 209 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Creating a Validator with ActionScript


Can also create an instance of a validator class with ActionScript import mx.validators.PhoneNumberValidator; private var v:PhoneNumberValidator; private function createValidator():void { v = new PhoneNumberValidator(); v.source = phoneInput; v.property = "text"; } The validator instance is declared outside the function body so it persists after the function has finished executing

Handling Required Values


By default, the required property is set to true for all validators; to validate a value only if data is entered, set the property value to false required="false"

Triggering validation with events


Trigger validation either in response to an event, or programmatically by calling a validators validate() method To trigger validation in response to an event, set the trigger and triggerEvent properties of the validator <mx:NumberValidator id="amountV" source="{amountInput}" property="text" trigger="{calcButton}" triggerEvent="click"/> <mx:TextInput id="numberInput"/> <mx:Button id="calcButton" label="Calculate"/> The text property of amountInput is required and must be in a valid numeric format Validation will be triggered when the user clicks calcButton The trigger property is set as a binding expression, and the triggerEvent as a simple text value

Pgina 210 de 274

ADOBE FLEX 3 Developing Rich Client Applications

When Validation Fails


When validation fails, Flex automatically displays the appropriate error message o Red box is displayed around the control that was validated o When user moves the cursor over the control, validation message is displayed next to it

Figure 7: Error displayed when the validator does not pass validation

Using the NumberValidator Class


Each validator subclass has a set of properties that allow you to turn on specific validation rules and set custom error messages The NumberValidator class validates for values that are valid numbers o Supports these validation properties NumberValidator Unique Properties Property minValue maxValue domain allowNegative required lowerThanMinError exceedsMaxError integerError invalidCharError requiredFieldError Description Minimum valid value Maximum valid value real=any number (default) int=integers only Boolean expression indicating whether negative values are allowed Boolean expression indicating whether value can be left blank Error message for minValue rule Error message for maxValue rule Error message for domain rule Error message when the value contains unacceptable characters Error message when required is true and value is left blank

Pgina 211 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 3: Validating Numeric Input


In this walkthrough, you will perform the following tasks: Set up a Validator tag to test if a value is a number Trigger the validation on a Text-Input field

Steps
1. 2. Open Forms_wt3.mxml. Run the application. Notice that if non-numeric values are entered in the TextInput controls, the form component displays incorrect values, since values from controls' text properties cant be cast as Number.
Figure 8: Tip calculator with invalid values

3. 4.

Open CalcForm_wt3.mxml from the forms folder. Go back to the code in Flex Builder and locate the <mx: Button> that triggers calculation. Set its id property to calcButton.

Instantiating NumberValidator Classes


5. After the Script block, insert an <mx:NumberValidator> tag to validate the amountInput control. Set the validator's properties as follows. id:amountV source: {amount Input} property:text trigger: {calcButton} triggerEvent: click requiredFieldError: Amount is required 6. Add another <mx:NumberValidator> tag to validate the percentInput control. Set the validator's properties as follows: id:percentV source: {percentInput} property: text trigger: {calcButton} triggerEvent: Click requiredFieldError:Enter a percentage domain: int integerError:Enter percent as a whole number 7. Run the application. Try these scenarios, clicking the Calculate button for each one. o Leave all values blank o Enter non - numeric values o Enter a fractional percent value

For each validation error, you should see a red box around the form control that contains the invalid data. Move your mouse over the control, and the appropriate error message appears. Note: While validation error messages are appearing, the incorrect calculator results are still being displayed.

Pgina 212 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Triggering validation with ActionScript


Can also trigger validation programmatically with explicit ActionScript commands Each validator class has a validate() method that causes its validation rules to be triggered The Validator class has a static validateAll() method to trigger validation on multiple Validator objects Benefits of using programmatic validation o Can incorporate logic in your ActionScript code to only run those validation rules needed at the moment o Returns information indicating whether validation was successful A decision can then be made as to whether to take other actions such as sending the form data to a server for processing

Suppressing automatic validation


To use programmatic validation, first disable automatic validation o Remove the validators trigger property o Set the validators triggerEvent property to a blank string <mx:PhoneNumberValidator id="pnV" source="{phoneInput}" property="text" triggerEvent=""/> Note: Since there is no event with a blank string as a name, setting triggerEvent to a blank string means that automatic validation never occurs.

Using the validate() method


All validator classes support the validate() method Use validate() to trigger validation on a single validator object validate() returns a ValidationResultEvent object ValidationResultEvent has a type property, which will be set to one of these constant values o ValidationResultEvent.VALID o ValidationResultEvent.INVALID Following code triggers validation programmatically and determines whether the source controls data is valid and ready for processing import mx.events.ValidationResultEvent; private function calculate():void { var event:ValidationResultEvent = myValidator.validate(); if (event.type ==ValidationResultEvent.VALID) { process data } else { display error message }

Pgina 213 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Triggering multiple validators


The Validator class static validateAll() method triggers validation on multiple validator objects Receives an array of Validator objects as its only arguments Returns an array containing ValidationResultEvent objects for each Validator that fails validation If the returned arrays length is 0, validation has succeeded var invalidArray:Array = Validator.validateAll( [amountV, percentV]); if (invalidArray.length == 0) { ... take actions for valid form ... } else { ... take actions for invalid form ... }

Pgina 214 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 4: Triggering Validation with ActionScript


In this walkthrough, you will perform the following tasks: Trigger data validation with ActionScript commands Detect whether data was valid and take an appropriate action

Steps
1. 2. Open CalcForm_wt4.mxml. Locate each of the existing validator objects. For each object, make these changes: o Remove the trigger property o Set the triggerEvent to an empty string

triggerEvent= "" 3. As the first line in the calculate function, call Validator.validateAll() to trigger validation on both validation objects.

var invalidArray:Array = Validator.validateAll([amountV, percentV]); Check to be sure that Flex Builder added an import statement for the Validator class. import mx.validators.Validator; 4. Wrap the code that dispatches the custom event with a conditional block that checks whether validation was successful.

if (invalidArray.length == 0) { var formData:CalcData = new CalcData(); formData.amount = Number(amountInput.text); formData.percent = Number(percentInput.text); var event:CalcEvent=new CalcEvent("calculate", formData); dispatchEvent(event); } 5. Add an else block that displays an error in an Alert dialog box:

else { Alert.show ("There are form errors", "Calculator } Check to be sure that an import statement was added for the Alert class. Import mx.controls.Alert;

Error*);

Pgina 215 de 274

ADOBE FLEX 3 Developing Rich Client Applications

6.

Run the application and test validation. You should see that validation triggered upon the button click, and the error message is displayed.

Figure 9: An Alert dialog triggered with programmatic validation

Summary
The Form container lays out data entry forms with a predefined layout system The Form container does not handle packaging of data or application navigation Forms are frequently created as custom MXML components Forms can share data with the application using custom event classes and value objects Validate form control values using the Validator classes Triggering validation with ActionScript gives you the best control over the validation process

Review
1. Which 3 MXML tags are used to build a Form custom component?

2.

Which property of the Formltem container causes nested controls to lay out left to right?

3.

Which method of the Validator classes triggers validation errors when a value is left blank?

4.

Which method of the Validator class is used to trigger multiple validator objects?

Pgina 216 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Retrieving XML Data with HTTPService


In this section of the course, you will retrieve XML data at runtime and handle the results with data bindings and event handlers. You will enhance the data handling by ensuring that faults are handled properly. You will also learn how to make HTTP requests to different domains.

Objectives
After completing this unit, you should be able to: Retrieve XML data at runtime Handle results with data bindings Handle results with event handlers Handle faults Make HTTP requests to different domains

Topics
In this unit, you will learn about the following topics: Retrieving XML data at runtime Handling results Handling results using an event handler Handling faults Making HTTP requests to different domains Making HTTP requests with parameters

Pgina 217 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Retrieving XML data at runtime


Instead of hardcoding data into your SWF, it is best to load data in dynamically at runtime One such source of data is XML data Some benefits of dynamically loading XML data at runtime are o If the data set is large, segments can be loaded at different times o Data might be dynamically generated and want the latest data

Using the HTTPService class


Retrieve via HTTP request o Use HTTPService class o Can make get/post requests to specified URL o Can use HTTP or HTTPS

Process for making HTTP requests


Create HTTPService object o No request is made at this time Make the HTTP request o Remote file retrieved

Creating the HTTPService object


Assign an instance name (id property) to later reference data returned Set url property to relative or absolute address of remote data file XML data retrieved from a file on same file system as MXML file <mx:HTTPService id="test" url="myfile.xml"/> XML data retrieved from a file on a remote file system <mx:HTTPService id="test" url="http://mydomain.com/myfile.xml"/> URL can be for static or dynamically generated XML data XML retrieved from a static file <mx:HTTPService id="test" url="http://mydomain.com/myfile.xml"/> XML retrieved from dynamically built data <mx:HTTPService id="test" url="http://mydomain.com/my.jsp"/>

Pgina 218 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Making the HTTPService request


Use the HTTPService send() method to make a service request Often invoke method either by user or system event Data retrieved on user click event <mx:Button label="Retrieve Data" click="test.send()"/> Data retrieved by system creationComplete event <mx:Application ... creationComplete="test.send()"/>

Handling results
After an HTTPService request executes, returned data is placed in the objects lastResult property o Access the data as [HTTPService_id].lastResult Example (assumes simple string returned) <mx:Application ... creationComplete="test.send()"/> <mx:HTTPService id="test" url="http://anysite.com/flexHTTP.cfm"/> <mx:Label text="{test.lastResult}"/> Returned data format is configurable using the resultFormat property Following table shows possible return formats

Format object xml flashvars

Description The value returned is XML and is parsed as a tree of ActionScript objects (this is the default) The value returned is XML and is returned as literal XML in an ActionScript XMLnode object The value returned is text containing name=value pairs separated by ampersands, which is parsed into an ActionScript object The value returned is text, and is left raw The value returned is XML and is returned as literal XML in an ActionScript XML object, which can be accessed using ECMAScript for XML (E4X) expressions The value returned is XML and is parsed as a tree of ActionScript objects. If the top level object is not an Array, a new Array is created and the result set as the first item If makeObjectBindable is true then the Array will be wrapped in an ArrayCollection By default, XML data is converted into an ArrayCollection

text e4x

array

Pgina 219 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Understanding the ArrayCollection results


After a HTTPService request executes, the returned XML data is placed in the operations lastResult property o Represented as an ActionScript ArrayCollection o Flex interprets the XML data to appropriate base types An ArrayCollection is a complex data structure ArrayCollection is the recommended class to use as a data provider Must import the class to use ArrayCollection import mx.collections.ArrayCollection; Using an ArrayCollection class has the following advantages o The elements of the ArrayCollection can be used in bindings that will continue to be monitored This is not the case with the normal Array class, once an element from an array is used in a binding it is no longer monitored o Implements both the ICollectionView and IList interfaces Provides rich set of tools for data manipulation For example, to retrieve an item of the collection, where n is the zero-indexed position of the item

arrayCollectionInstance.getItemAt(n)

Using results in data bindings


The returned ArrayCollection can be used in data bindings

Figure 1: XML data converted into an ArrayCollection

Pgina 220 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Point at the repeating node to use it as a data provider <mx:DataGrid id="testList" dataProvider="{serviceid.lastResult. sandwichMenu.sandwich}"/> Note: The DataGrid will be used in this module as a way to dump data to be sure it is retrieved correctly. In a later module we will cover the DataGrid in depth. Use methods of the ArrayCollection to reference a value in a node serviceid.lastResult.sandwichMenu.sandwich. getItemAt(0).name

Pgina 221 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 1: Retrieving data at runtime with HTTPService


In this walkthrough, you will perform the following tasks: Create and configure an HTTPService object Use the send( ) method of an HTTPService object Display data returned from the HTTPService

Steps
Import the HTTPService Project
1. 2. Select File > Import > Flex Project. Import project from Archive File. o Browse to: <installDirectory>/adobeTraining/f3rca/ HTTPServiceProject.zip o Click Open o Click Finish Close all unrelated projects. Open sandwichData.xml in the assets folder in the src folder at the root of the HTTPService project and examine the XML data you will be working with in this walkthrough.

3. 4.

Creating an HTTPService object


5. 6. Open the HTTPService_wt1.mxml file in the src folder at the root of the project. Add an HTTPService tag to with an id property set to sanData. Set the url property to point to the XML file located in the assets folder, assets/sandwichData.xml . The completed HTTPService tag should appear as follows.

<mx:HTTPService id="sanData" url="assets/sandwichData.xml"/>

Making the HTTP request


7. 8. Add a creationComplete event to the Application tag. Use inline ActionScript to invoke the send( ) method of the sanData HTTPService.

Using the results in bindings


9. Below the HTTPService tag insert an DataGrid tag and bind the lastResult.sandwichMenu.sandwich from the sanData request to the DataGrid's dataProvider property.

<mx:DataGrid dataProvider="{sanData.lastResult.sandwichMenu.sandwich}" /> 10. Run the application. You will see the data displayed in the DataGrid

Pgina 222 de 274

ADOBE FLEX 3 Developing Rich Client Applications 11. Use a Label control to display the name property of the fourth element of the ArrayCollection by using the getItemAt() method. <mx:Label Text="{sanData.lastResult.sandwichMenu.sandwich.getItemAt(3).name} "/> Note: ArrayCollection indices are zero-based. 12. Run the application. You should see the word Pacific displayed below the DataGrid.

Handling results using an event handler


Use HTTPService result event to specify the function to be called when data is returned successfully The class of the Result Event object is mx.rpc.events.ResultEvent and must be imported for use You can manipulate the returned data before using it o Often will have to assign it to a variable whose scope is the page rather than the function o Pass the event object as the parameter The event object contains a result property with the data returned for this particular event <mx:HTTPService id="test" url="http://mysite.com/flexHTTP.cfm" result="httpResultHandler(event)" />

Exampl e
<mx:Script> <! [CDATA[ import mx.collections.ArrayCollection; import mx.rpc.events.ResultEvent; [Bindable] private var sandwiches:ArrayCollection; private function sanDataHandler(event:ResultEvent):void { sandwiches=event.result.sandwichMenu.sandwich; } ]]> </mx:Script> <mx:HTTPService id="sanData" url="http://localhost:8500/httpservice /sandwichXML.cfm" result="sanDataHandler(event)"/> <mx:DataGrid dataProvider="{sandwiches}"/> <mx:Label text="{sandwiches.getItemAt(3).name}"/>

Note: Do not confuse the lastResult property of the HTTPService class and the result property of the Event class.

Pgina 223 de 274

ADOBE FLEX 3 Developing Rich Client Applications You use the lastResult property in data bindings directly to the returned results, and use the result property in an event handler when you pass the event object to the event handler function.

Pgina 224 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 2: Using a result event


In this walkthrough, you will perform the following tasks: Specify a result event in the HTTPService tag Create a result handler Display the data returned in the event object

Steps
1. Open the HTTPService_wt2.mxml file in the src folder at the root of the project.

Using a result event and handler


2. In the HTTPService tag, call a function named sanDataHandler with the result event. Pass the event object as a parameter.

result="sanDataHandler(event)" 3. 4. After the Application tag, insert a Script block. In the Script body, import the

mx.collections.ArrayCollection and mx.rpc.events.ResultEvent classes. Note: You can also just use the classes as datatypes and Flex Builder will automatically import the classes for you. 5. After the import statements, declare a Bindable, private variable named sandwiches, datatyped as an ArrayCollection.

[Bindable] private var sandwiches:ArrayCollection; 6. Create a private function named sanDataHandler which accepts a parameter named event, datatyped as ResultEvent. The function will not return a value, so data type it as void.

private function sanDataHandler(event:ResultEvent) : void { }

Using the debugger to examine the returned data


7. 8. 9. Place a breakpoint on the same line as the closing brace of the function you just built. Debug the application. When process flow returns to the Flex Builder debugger, examine the event object in the Variables view with your instructor.

Pgina 225 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Figure 2: debugging the data returned by HTTPService

10. Terminate the debugging session and return to the Flex Development perspective.

Displaying data
11. In the sanDataHandler function, assign the sandwiches variable (the new instance of the ArrayCollection class) the returned data stored in the event object: sandwiches = event.result.sandwichMenu.sandwich;| 12. Change the DataGrid so the dataProvider is bound to sandwiches. <mx:DataGrid dataProvider="{sandwiches}"/> 13. Change the text property in the Label so it uses the sandwiches variable. <mx:Label text="{sandwiches.getItemAt(3).name)"/) 14. Run the application. You should see the dump of data in the DataGrid followed by the sandwich name, the same as it was displayed in the first Walkthrough.

Pgina 226 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Handling faults
The HTTPService dispatches a FaultEvent when the data service has a problem returning result data Specify a handler function for the fault event to execute if the FaultEvent is dispatched <mx:HTTPService id="test" url="http://mysite.com/flexHTTP.cfm" result="httpResultHandler(event)" fault="faultHandler(event)" requestTimeout="60"/>

A FaultEvent is dispatched when a destination cannot successfully process a message due to a connection, server, or application-level failure o Has properties target (always available in an event), type (always available in an event) and fault, among others A FaultEvent is also dispatched when the value of the requestTimeout property is exceeded The fault property, of the FaultEvent class, is a Fault object that has useful properties for displaying error messages o The Fault class has the following properties (all of datatype String) faultDetail: Any extra details about the fault faultCode: A simple code describing the fault faultString: Text description of the fault message: The three properties above concatenated

Displaying messages with an Alert pop-up


When displaying messages, such as faults, you can use a pop-up to display them using the Alert class Import from mx.controls.Alert show() method with the first two parameters of that method, most often used (in the following order) o text - Shown in the body of the pop-up o title - Shown in the header of the pop-up An OK button appears by default to close the Alert pop-up Example <mx:Script> <![CDATA[ import mx.controls.Alert; private function alerted():void { Alert.show("This first parameter is the text of the alert box", "Alert Box Title - 2nd Parameter"); } ]]> </mx:Script> <mx:Button label="Alert me" click="alerted();"/>

Pgina 227 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Figure 3: The alert pop-up displayed when the Button is clicked

These messages are for development. More robust error handling would need to be implemented for production applications

Pgina 228 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 3: Handling a fault event


In this walkthrough, you will perform the following tasks: Specify a handler function to execute when a FaultEvent is dispatched Use the Flex Builder debugger to examine the fault object In the fault handler use an Alert pop-up to display fault information

Steps
1. 2. Open HTTPService_wt3.mxml. Run the application. You should see an unhandled runtime error.

Specifying a fault handler


3. In the HTTPService tag, use the fault event to execute a function named faultHandler. Pass the event object as a parameter.

fault="faultHandler(event)"

4.

In the Script block, create a private function named faultHandler which accepts a parameter named event, data typed as mx.rpc.events.FaultEvent and returns void.

private function faultHandler(event:mx.rpc.events.FaultEvent):void } { Note: You could have imported this class and then just used FaultEvent as the datatype. The advantage to using the complete path in this case is that you can just copy and paste this fault handler function into other files and not have to also do an import statement.

Using the debugger to examine the fault event object


5. 6. 7. Place a breakpoint on the same line as the closing brace of the faultHandler function. Debug the application. When process flow returns to the Flex Builder debugger, examine the event object in the Variables view with your instructor.

Figure 4: The event object displayed in the Variables view

Pgina 229 de 274

ADOBE FLEX 3 Developing Rich Client Applications

8.

Terminate the debugging session.

Displaying the fault data in an Alert pop-up


9. In the faultHandler function, create a variable local to the function named eventInfo datatyped as String.

10. Assign this variable the literal text event target:, followed by the actual event.target value, followed by two newline characters (\n): Var eventInfo:String="event target: "+event.target+"\n\n"; 11. Using the concatenation assignment operator (+=), add to the eventInfo variable information about the event type in the same manner you displayed target information. eventInfo+="event type: "+event.type+"\n\n"; 12. Use the mx.controls.Alert class show( ) method to display the eventInfo variable as the text in an Alert pop-up. Make the title Event Information. mx.controls.Alert.show(eventInfo, "Event Information"); Note: You could have explicitly imported the Alert class with an import statement, but as with the FaultEvent, you have implicitly imported it to make this function more easily portable.

13. Run the application. You will see the Alert box displaying the fault event information. 14. Above the existing code in the faultHandler function, add the following to display properties of the fault object. var faultInfo: String="fault code: "+event.fault.faultCode+"\n\n"; faultInfo+="fault string:"+event.fault.faultString+"\n\n"; mx.controls.Alert.show(faultlnfo, "Fault Information"); 15. Run the application. You should see the Alert boxes (one on top of the other) displaying the event information, then when you click OK on the first Alert pop-up, you will see the fault information.

Pgina 230 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Making HTTP requests to different domains


By default, Flash Player does not allow an application to receive data from a domain other than the domain from which it was served

Figure 5: Default Flash Player security

Using cross-domain policy files


To make data available to SWF files in different domains, use a cross-domain policy file A cross-domain policy file is an XML file that provides a way for the server to indicate that its data and documents are available to SWF files served from other domains The default policy file is named crossdomain.xml and resides at the root directory of the server that is serving the data

Pgina 230 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Figura 6: Security using a crossdomain.xml file

Example to allow access from any domain <cross-domain-policy> <allow-access-from domain="*"/> </cross-domain-policy>

Pgina 231 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 4: Testing cross-domain policy


In this walkthrough, you will perform the following tasks: Request data and see the error returned from HTTPService Create a crossdomain.xml file Validate that the HTTPService works

Steps
1. 2. 3. Open the HTTPService_wt4_127001.mxml and HTTPService_wt4_localhost.mxml files from the src folder at the root of the application. Notice the code is identical except for the url property of the HTTPService tag. Both of these files have been compiled and deployed to the directory <installDirectory> \ColdFusion8\wwwroot\flex\http Service.

Browsing both files that request data


4. 5. Browse http://127.0.0.1 :8500/flex/httpService/ HTTPService_wt4_l27001.swf and you will see the data is displayed correctly. Browse http://127.0.0.1:8500/flex/httpService/ HTTPService_wt4_localhost.swf and you will see a "Security error accessing url" message. This is because the SWF was served from 127.0.0.1:8500 but the data request went to localhost:8500.

Note: In networking terms 127.0.0.1 and localhost are the same, but Flash Player compares addresses as strings, in which case they are obviously not the same.

Creating a crossdomain.xml
6. 7. 8. Open the file crossdomain.xml in the assets directory and notice it allows Flash Player from any domain to access data. Copy the file crossdomain.xml into the directory <installDirectory>\ColdFusion8\wwwroot. Browse http://127.0.0.1:8500/flex/httpService/ HTTPService_wt4_localhost.swf again and you should see the data appear. You see that crossdomain.xml is doing its job.

Pgina 232 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Making HTTP requests with parameters


Most services accept parameters that specify the exact nature of the data to be generated and subsequently sent back to the client application Two distinct ways to make a HTTPService request with parameters o Explicit parameter passing o Parameter binding

Using explicit parameter passing


Provide input to a service in the form of parameters to an ActionScript function Similar to calling methods in Java Cannot use automatic Flex data validators Example 1 - HTTPService call with a send() method that takes a variable as its parameter o Value of the variable is an Object <mx:HTTPService id="demoService" destination="http://www.website.com/data.cfm"/> <mx:Button click="demoService.send({demo_param: 'demo_value'});"/> Example 2 - HTTPService call with an Object as a send() method parameter that provides query parameters o Use cancel() method to cancel any pending HTTPService calls

<mx:Script> <![CDATA[ public function callDemoService():void { demoService.cancel(); var params:Object=new Object(); params.demo_param='demo_value'; demoService.send(params); } ]]> </mx:Script> <mx:HTTPService id="demoService" destination="http://www.website.com/data.cfm"/> <mx:Button click="callDemoService();"/>

Pgina 233 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Using parameter binding


Copy data from user-interface controls or models to request parameters Only available for data access components that you declare in MXML Can apply validators to parameter values before submitting requests to services Example o Use the send() method with no parameters <mx:HTTPService id="demoService" destination="http://www.website.com/data.cfm"> <mx:request> <demo_param>{demoValue.text}</demo_param> </mx:request> </mx:HTTPService> <mx:TextInput id=demoValue/> <mx:Button label="Get Demo Service Data" click="demoService.send();"/>

Pgina 234 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 5: Using HTTPService with parameters


In this walkthrough, you will perform the following tasks: Call HTTPService with a parameter using explicit parameter passing Call HTTPService with a parameter using parameter binding

Steps
Note: If the result data has zero or one element, an ArrayCollection is not created in the result. The sanDataHandler function in this example has been modified to validate that the event result has a valid ArrayCollection.

Calling the sandwichData service with no parameters


1. Open the HTTPService_wt5.mxml file and HTTPService_wt4_localhost.mxml files from the src folder at the root of the project.

Notice that the code in the two files is identical except for the HTTPService url property. The sandwichData.cfm is a ColdFusion template that filters the data contained in the sandwichData.xml file. Without any parameters passed via HTTPService, the sandwichData.cfm service simply returns the entire contents of the sandwichData.xml file. 2. Run HTTPService_wt5.mxml. The output generated should appear the same as that generated previously by HTTPService_wt4_localhost.mxml.

Note: In walkthrough 4 you browsed the compiled and deployed version of HTTPService_wt4_localhost.mxml (http://127.0.0.1:8500/flex/httpService/ HTTPService_wt4_localhost.swf) 3. 4. 5. 6. Close HTTPService_wt4_localhost.mxml. Switch to HTTPService_wt5.mxml. Remove the creationComplete event from the beginning Application tag. Delete the Label tag.

Sending a HTTPService request having an explicit parameter using a click event


7. Create a Button tag with a label property set to Get Sandwiches. Add a click event set to send a sanData HTTPService request with a parameter Object name-value pair of {type:'Cold'}.

<mx:Button click="sanData.send({type: 'Cold'});" label="Get Sandwiches"/) 8. Run HTTPService_wt5.mxml and then click the Get Sandwiches button. You will see that all of the Cold type sandwiches listed in the DataGrid.

Pgina 235 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Sending a HTTPservice request having an explicit parameter from a function


9. As the last code in the Script block, create a public function named callSanDataService having a return type of void.

public function callSanDataService():void { } 10. In the function, use the Cancel method on the SanData HTTPService to cancel any pending requests that may have failed. sanData.cancel(); 11. Create an instance of type Object named params. var params:Object=new Object(); 12. With the params Object, create a property named type having a value of Grilled params.type='Grilled'; 13. In the send method of the SanData HTTPService request, pass the parameter params. sanData.send(params); The code should appear as follows. public function callSanDataService():void { sanData.cancel(); var params:0bject = new Object(); params.type='Grilled'; sanData.send(params); } 14. Change the click event on the Button control to use the callSanDataService function. <mx:Button click="callSanDataService();" label="Get Sandwiches"/> 15. Run HTTPService_wt5.mxml and then click the Get Sandwiches button. You will see all of the Grilled type sandwiches listed in the DataGrid.

Calling the sandwich Data service using parameter binding


16. Above the Button control, add a TextInput control having an id property of sanType. 17. Remove the ending / from the HTTPService tag. Then add a closing HTTPService tag to match the beginning HTTPService tag. 18. Inside the HTTPService block, add a request block. 19. Inside the request block, create child tags named type which represent name of the parameter the service expects. Within the child tags, add a binding to the sanType text property.

Pgina 236 de 274

ADOBE FLEX 3 Developing Rich Client Applications <type>{sanType.text}</type>

Pgina 237 de 274

ADOBE FLEX 3 Developing Rich Client Applications

20. Check that the HTTPService block appears as follows: <mx:HTTPService id="sanData" url="http://localhost:85OO/flex/httpService/sandwichData.cfm" result="sanDataHandler(event)" fault="faultHandler(event)"> <mx:request> <type> {sanType.text}</ type> </mx:request> </mx:HTTPService> <mx:TextInput id="sanType" /> 21. Change the click event value on the Button control to invoke the send method of the sanData HTTPService. <mx:Button click="sanData.send()" label="Get Sandwiches"/> 22. Run HTTPService_wt5.mxml. In the TextInput area, enter Triple Decker and then click the Get Sandwiches button. Note: The input value is case sensitive. You will see all of the Triple Decker type sandwiches listed in the DataGrid.

Pgina 238 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Summary
Load data in dynamically at runtime using the HTTPService class After an HTTPService operation executes, returned data is placed in the objects lastResult property and can be referenced as serviceid.lastResult Use HTTPService result event to specify the function to be called when data is returned successfully HTTPService triggers a fault event when the data service has a problem returning result data o Code an even handler for these situations By default, Flash Player does not allow an application to receive data from a domain other than the domain from which it was served o Create a crossdomain.xml file to allow access to other domains

Review
1. What are general steps needed to make an HTTP service request? 2. What method of the HTTPService class do you use to make the actual service request? 3. List and describe the five options for the resultFormat property of the HTTPService class? 4. Describe the difference between, and when you would use each of, the lastResult property of the HTTPService class and the result property of the ResultEvent class. 5. What are the advantages of using an ArrayCollection over an Array? 6. When is the fault event of the HTTPService class broadcast? 7. What purpose does the crossdomain.xml file serve?

Pgina 239 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Displaying Data Using the DataGrid


In this unit, you will focus on using the DataGrid control. This control has the capability to display complex data in rows and columns and is customizable.

Objectives
After completing this unit, you should be able to: Understand the capabilities of the DataGrid control Use data structures to populate a DataGrid control Customize the columns of a DataGrid control Use a function to format the DataGrid columns Customize DataGrid columns using item Tenderers and item editors Use the TileList and HorizontalList with item Tenderers Retrieve data using the change event in conjunction with the sel ected I tem property

Topics
In this unit, you will learn about the following topics: Using the DataGrid control Specifying DataGrid columns Formatting DataGrid columns Using item Tenderers and item editors Inline item Tenderers and item editors Item Tenderer and item editor components Using the TileList and HorizontalList Using events and selected items with list-based components

Pgina 240 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Using the DataGrid control


DataGrid control inherits from the ListBase class o Can show multiple columns of data o A formatted table whose items can be editable

Figure 1: A DataGrid control displaying data in a row-column format

DataGrid features o Resizeable columns o Customizable columns and column headers o Items can be set as editable o Multiple item selection can be set o Allows for customized item display o Paging of data o Drag and drop capability DataGrid tag example <mx:DataGrid columns="No default." dataProvider="No default." sortableColumns="true|false" . . . />

Supplying data to a DataGrid


Data for DataGrid is usually a collection of objects with multiple properties that are displayed as separate columns The dataProvider property is used to bind to the collection of objects

ArrayCollections
Best practice is to bind the dataProvider property to an ArrayCollection Must import the class to use it mx.collections.ArrayCollection If data is stored in an array, it should be converted into an ArrayCollection Class Using the ArrayCollection has the following advantages

Pgina 240 de 274

ADOBE FLEX 3 Developing Rich Client Applications o The elements of the ArrayCollection can be used in bindings that will continue to be monitored This is not the case with the normal Array class; once an element from an array is used in a binding, it is no longer monitored Implements both the ICollectionView and IList interfaces Provides rich set of methods for data manipulation Recommended data structure when data used as a dataProvider

o o

Note: An array is for data storage, not for use in bindings Code example: Populating a DataGrid from a Model <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*" layout="absolute" creationComplete="restaurants = new ArrayCollection(myDataModel.item)"> <mx:Model id="myDataModel"> <item> <key>0</key> <style>Thai</style> <number>6</number> </item> <item> <key>1</key> <style>Indian</style> <number>14</number> </item> </mx:Model> <mx:Script> <![CDATA[ import mx.collections.ArrayCollection; [Bindable] public var restaurants:ArrayCollection; ]]> </mx:Script> <mx:DataGrid dataProvider="{restaurants}"/> </mx:Application> You can also embed the XML instead of defining it inline <mx:Model id="myModel" source="datagriddata.xml"/> One column created for each property Order of columns not predictable Column headers are set to element names

Figure 2: Default columns of a DataGrid

Pgina 241 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Demonstration 1 : Displaying Simple XML Data in a DataGrid


In this demonstration, your instructor will perform the following tasks: Display external XML data from an HTTPService in a DataGrid

Steps
Import the DataGrid Project
1. 2. Select File > Import > Flex Project. Import project from Archive File. Browse to: <installDirectory>/adobeTraining/f3rca/ DataGridProject.zip Click Open Click Finish Close all unrelated projects.

3.

Display XML data


4. Open the file assets/datagriddata.xml from the src folder at the root of the project. Examine the data structure. Open the file DataGrid_demo1.mxml and run it. You should see a DataGrid populated by its dataProvider, an ArrayCollection. The ArrayCoIlection is populated from XML data from the HTTPService results.

5.

Pgina 242 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Specifying DataGrid columns


Each column in the DataGrid is an instance of the DataGridColumn class Explicitly create DataGridColumn objects to configure the DataGrid o Limit columns displayed o Set order of columns displayed o Change column header text o Set column formatting in various ways <mx:DataGridColumn dataField="No default" headerText ="No default"/> To use, nest DataGridColumn objects inside the columns property

<mx:DataGrid dataProvider="{restaurants}"> <mx:columns> <mx:DataGridColumn dataField="style" headerText="Style" /> <mx:DataGridColumn dataField="number" headerText="Available" /> </mx:columns> </mx:DataGrid>

Specifying DataGrid columns result

Figure 3: DataGridColumns specified

Pgina 243 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 1: Specifying DataGrid columns


In this walkthrough, you will perform the following tasks: Retrieve restaurant review data Customize two columns of data by utilizing DataGridColumns

Steps
Import the DataGrid Project
1. 2. If the DataGrid project is not already imported, select File > Import > Flex Project. Import project from Archive File. o Browse to: <installDirectory>/adobeTraining/f3rca/ DataGridProject.zip o Click Open o Click Finish Close all unrelated projects. Open the DataGrid_wt1.mxml file from the src folder at the root of the DataGrid project.

3. 4.

Viewing the DataGrid with the returned data


5. 6. Open the XML file that is listed in the HTTPService component. Add a DataGrid component and set the dataProvider property to bind to the reviewList ArrayCollection already created in the file.

dataProvider="{reviewList}" 7. Run the application. You should see the DataGrid with 7 columns and header text set to the XML element names.

Using DataGridColumn
8. Remove the / from the end of the DataGrid tag and add a new closing DataGrid tag to create a tag set. <mx:DataGrid dataProvider="{reviewList}" > </mx:DataGrid> 9. Add a child <mx:columns> tag set to the DataGrid.

10. "Within the columns tag set, add a DataGridColumn tag to display the reviewer data by specifying the dataField property value, and set the headerText to Reviewer. <mx:DataGridColumn dataField="reviewer" headerText="Reviewer" />

Pgina 244 de 274

ADOBE FLEX 3 Developing Rich Client Applications

11. Add another DataGridColumn to display the review_date data and set the headerText to Review Date. <mx:DataGridColumn dataField="review_date" headerText="Review Date"/> 12. Be sure your DataGrid tag appears as shown here: <mx:DataGrid dataProvider="{reviewList}"> <mx:columns> <mx:DataGridColumn dataField="reviewer" headerText="Reviewer "/> <mx:DataGridColumn dataField="review_date" headerText="Review Date"/> </mx:columns> </mx:DataGrid> 13. Run the application. You should see the DataGrid with only the columns you specified, Reviewer and Review Date.

Formatting DataGrid columns


To control the display of data in a DataGrid column, use the labelFunction property o Property of the DataGridColumn class Also available in other list bassed controls o Specify a user defined function to properly format the column data Do not use parentheses, just use the function name <mx:DataGridColumn dataField="myDate" headerText="Date" labelFunction="dateFormatFunc"/> Creating a formatting function o Specify two arguments when using a labelFunction with a DataGrid The first parameter datatyped as Object, traditionally named item, but can have any variable name (The first parameter holds the data object passed from the DataGrid and represents the row of data) The second parameter is the column name, datatyped as DataGridColumn o o Use the return statement to send back the formatted data string The label function below displays the date, followed by the actual rating this shows you can use data from the entire row in the label function, not just data from the column passed to the function

private function dateFormatFunc(item:Object, review_date:DataGridColumn):String { return myDate.format(item.review_date) + ": "+ item.rating; } ... <mx:DateFormatter id="myDate" formatString="DDMMM- YY"/>

Pgina 245 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Creating reusable label functions


The previous function will work fine, but only for the particular column for which it was built o Need a generic solution to handle multiple date columns o Relieves us from having to write multiple, column-specific functions Instead of having to use a reference to a specific column name, use the dataField property of the DataGridColumn class o dataField property can access the name of the field or property in the data associated with the column o In the example, review_date refers to the same as column.dataField In the function, instead of referring to the column as item.review_date (or the specific column name), use item[column.dataField]

Pgina 246 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 2: Formatting data in DataGrid columns


In this walkthrough, you will perform the following tasks: Use a labelFunction to format dates display dates in a DataGridColumn

Steps
1. Open the DataGrid_wt2.mxml file from the src folder at the root of the project.

Instantiate a DateFormatter
2. 3. Below the HTTPService tag, insert a DateFormatter component. Give the DateFormatter an id of my Date and set the formatString property to DD-MMM-YY.

Setting the labelFunction for the DataGridColumn


4. Locate the review_date DataGridColumn and add the labelFunction property and set it to call the dateFormat function.

labelFunction="dateFormat" 5. Inside of the existing Script block, create a private function named dateFormat, datatyped as String, that accepts two parameters named item, datatyped as Object, and another parameter named review_date datatyped as DataGridColumn.

private function dateFormat(item:Object, review_date:DataGridColumn):String { } 6. Instruct the function to return the formatted review_date from the item object and the corresponding score, separated by a colon and space. "

return myDate.format(item.review_date) + ": + item.rating; 7.

Change the headerTextproperty value to Review Date and Rating and set the width property to l50 to ensure all the header text is displayed. Run the application. You should see the dates in the DataGrid are formatted as specified by the DateFormatter tag, followed by the ratings. To create a more generic label function, change the signature of the function to accept the item as is, then replace review_date with column.

8.

9.

10. In the function itself, replace the reference to the specific column item. review_date with item[column.dataField].

Pgina 247 de 274

ADOBE FLEX 3 Developing Rich Client Applications

11. Your new function should appear as follows: private function myDateFormat(item:Object, column:DataGridColumn):String { return myDate.format(item[column.dataField]) + ": " + item.rating; } 12. Run the application. You should see the date column displayed exactly it was before making the label function reusable.

Using item renderers and item editors


Item renderers and item editors customize the appearance and/or behavior of items in list-based components o List-based components include DataGrid, List, Tree, Menu, TileList Each list-based control has a default item renderer which is used to display data o For instance, the DataGrid assumes each item will display a text string In a DataGrid, if you wish to display anything else you must use an item renderer or item editor o Normal DataGrid, one text string per item

Figure 4: Normal item renderer

Item renderer used to display two strings in one item

Figure 5: Two strings in one item

Item renderer used to display a CheckBox

Pgina 248 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Figure 6: a ChekBox in an item

Item renderers versus item editors


Both item renderers and item editors receive data in a data property from a list control The item renderer uses the data for display

Figure 7: item renderer displays data

Note: An item renderer can act as an item editor by setting the rendererIsEditor property to true. The item editor can pass data back from the list control that then becomes the new value of the edited item o Only possible in the list-based controls DataGrid, List and Tree

Figure 8: item renderer displays data

Visually, item renderers and item editors behave differently o An item renderer is used all the time o An item editor is used only when item is being edited Example: Both a NumericStepper and CheckBox are being used as item editors o Editing an item with a NumericStepper as an item editor

Pgina 249 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Figure 9: Using a NumericStepper as an item editor

This is most likely the behavior you want; the NumericStepper only displays when an item is being edited Editing an item with CheckBox as an item editor

Figure 10: Using a CheckBox a item editor

This is most likely NOT what you want; the CheckBox only appears when the item is being edited Editing an item with a CheckBox as an item renderer

Figure 11: Using a ChekBox as item renderer

This is most likely what you want; the CheckBox is always visible Note: In this last case, the rendererIsEditor property was set to true so an item renderer could also return the value of the CheckBox, which an item renderer normally cannot do. Tip: If an item editor or an item renderer with the rendererIsEditor property set to true are used, the DataGrids editable property must be set to true.

Pgina 250 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Types of item renderers and item editors


There are three types of item renderers and item editors o Drop-in o Inline o Component

Drop-in item renderers and item editors


Specify a control as the value for item renderer or item editor o Use itemRenderer property for item renderer o Use itemEditor property for item editor If data will be returned (either using an item editor or item renderer with rendererIsEditor set to true), use the editorDataField property to specify the property of the item editor that contains the new data The following controls can be used for drop-in item editor Controls that can be used as a drop-in Button CheckBox DateField Image Label Examples o item renderer drop-in <mx:DataGridColumn dataField="reorder" headerText="Reorder" itemRenderer="mx.controls.CheckBox" editorDataField="selected" rendererIsEditor="true"/> NumericStepper Text TextArea TextInput

item editor drop-in <mx:DataGridColumn dataField="quantity" headerText="Quantity" itemEditor="mx.controls.NumericStepper" editorDataField="value"/>

When used with a DataGrid, must set the DataGrid s editable property to true

Pgina 251 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 3: Using a drop-in item editor


In this walkthrough, you will perform the following tasks: Make the DataGrid editable Add a NumericStepper as a drop-in item editor

Steps
1. 2. Open the DataGrid_wt3.mxml file from the src folder at the root of the project. Run the application and note that when you click on a rating it is not editable.

Making the DataGrid editable


3. Add to the DataGrid component an editable property and set it equal to true. <mx:DataGrid dataProvider="{reviewList}" editable="true"> 4. Add to the DataGridColumn tag that displays the reviewer name an editable property and set it equal to false.

<mx:DataGridColumn dataField="reviewer" headerText="Reviewer" editable="false"/> Note; You cannot set just one DataGridColumn editable. You must set the entire DataGrid as editable, then set the editable property to false on those DataGridColumns you do not want users to edit.

Adding a drop-in item editor


5. Locate the DataGridColumn tag that displays the rating. Add an itemEditor property and set it equal to mx.controls.NumericStepper. To that same DataGridColumn tag, also add an editorDataField property and set it equal to value.

6.

<mx:DataGridColumn dataField="rating" headerText="Rating" itemEditor="mx.controls.NumericStepper" editorDataField="value"/> 7. Run the application. You should see when you click on a rating, a NumericStepper will appear so you can edit the rating. Note that even though the rating system is from 1 -5, you are able to use the defaults of the NumericStepper of 0-10.

Pgina 252 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Making the editor a renderer


8. Copy the entire DataGrid and paste a copy below the existing one. 9. In the new DataGrid, change the DataGridColumn itemEditor property to itemRenderer. 10. Add a rendererIsEditor property and set it equal to true. <mx: DataGridColumn dataField="rating" headerText="Rating" itemRenderer="mx.controls.NumericStepper" editorDataField ="value" rendererIsEditor="true"/> 11. Run the application. You should see the difference between the top DataGrid that uses an item editor and only shows the NumericStepper when an item is being edited, and item renderer, which always shows the NumericSteppers. In this example, the item editor is the better choice.

Inline item renderers and item editors


Drop-in item renderers easy to use, but you cannot control the item renderer or item editor o For example, the ability to set a minimum and maximum on NumericStepper Use inline item renderers and item editors to have complete control over the item rendering and editing To create an inline item renderer or item editor o In a DataGridColumn tag block, specify itemRenderer or itemEditor using nested subtags o Nest a Component tag block o Nest a control; can be simple or complex Simple inline item editor example <mx:DataGridColumn dataField="rating" headerText="Rating"> <mx:itemEditor> <mx:Component> <mx:NumericStepper minimum="1" maximum="5"/> </mx:Component> </mx:itemEditor> </mx:DataGridColumn> Complex inline item renderer example <mx:DataGridColumn dataField="Album"> <mx:itemRenderer> <mx:Component> <mx:VBox> <mx:Text id="mealName" selectable="false" width="100%" text="{data.meal}"/> <mx:Image id="mealImage" height="45" source="{data.mealImg}"/> </mx:VBox> </mx:Component> </mx:itemRenderer> </mx:DataGridColumn>

Pgina 253 de 274

ADOBE FLEX 3 Developing Rich Client Applications

The following are allowed in an inline item renderer Allowed in an inline item renderer Binding tags Effect tags Metadata tags Model tags Script tags Service tags State tags Style tags XML tags id attributes, except in topmost component

Walkthrough 4: Using an inline item editor


In this walkthrough, you will perform the following tasks: Make the DataGrid editable Add a NumericStepper as an inline item editor

Steps
1. 2. Open the DataGrid_wt4.mxml file from the src folder at the root of the project. Run the application and note that when you click on a rating it is not editable.

Making the DataGrid editable


3. Add to the DataGrid component an editable property and set it equal to true.

Adding an inline item editor


Locate the DataGridColumn tag that displays the rating. Change the single DataGridColumn into a DataGridColumn tag set with opening and closing tags. 5. In the opening DataGridColumn tag, add an editorDataField property and set it equal to v value. 6. Nest a childitemEditor tag block in the DataGridColumn tag block. 7. Nest a child Component tag block in the itemEditor tag block. 8. In the Component block, insert a NumericStepper component. 9. In the NumericStepper, set the minimum property to 1 and the maximum property to 5. 10. Confirm that the DataGridColumn code appears as follows. 4. <mx:DataGridColumn dataField ="rating" headerText="Rating" editorDataField ="value"> <mx:itemEditor> <mx:Component> <mx:NumericStepper minimum="1" maximum="5"/> </mx:Component) </mx:itemEditor> </mx:DataGridColumn> 11. Run the application. You should see when you click on a rating, a NumericStepper will appear so you can edit the rating. Note that the rating system is now constrained from 1-5.

Pgina 254 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Item renderer and item editor components


A complex inline item renderer might be better built as a separate component o Provides greater flexibility and functionality o Easier to reuse Build the item renderer or item editor component much like you did the inline version, but in a separate file, just as you have learned to build components The data for each item in the column is passed to the component which displays the data as determined in the component o Reference the data as data Item renderer and item editor components can be written in MXML or ActionScript o o If written in ActionScript, should extend the UIComponent class or any subclass of the UIComponent class When using, do not specify the extension

Example of an item renderer component o Displays two Labels o Component is named Details.mxml <?xml version="1.0" encoding="utf-8"?> <mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" verticalScrollPolicy="off" horizontalScrollPolicy="off"> <mx:Label text="Price: {data.product_price}"/> <mx:Label text="Category Name: {data.category_name}"/> </mx:VBox> Note: It is often necessary to turn off verticalScrollPolicy and horizontalScrollPolicy in an item renderer component. Using the item renderer component <mx:DataGridColumn dataField="product_price" headerText="Price" itemRenderer="Details"/> Will need to add the variableRowHeight property set equal to true when using component item renderers and editors If files are in different folders, must use a path to point to the item renderer itemRenderer="itemRenderers.Details"

Pgina 255 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Walkthrough 5: Using a component item renderer


In this walkthrough, you will perform the following tasks: Create a new item renderer component Add an itemRenderer property to a DataGridColumn

Steps
1. Open the DataGrid_wt5.mxml file from the src folder at the root of the project

Creating the item renderer component


2. 3. Right click on the DataGrid project and select New > MXML Component. Be sure the DataGrid project is selected, then enter the following values. o File Name: RatingDetai1.mxml o Base Component: VBox o Width: Remove value o Height: Remove value Click Finish. In the VBox, add horizontalScrollPolicy and verticalScrollPolicy properties and set both to off. Just after the VBox container, insert a DateFormatter component with an id of simpleDate and the formatString set to DD- MMM-YY. Following the DateFormatter, insert a Label control with the text property displaying the literal text Rating:, followed by a binding to the rating column.

4. 5. 6.

7.

<mx:Label text="Rating:{data.rating)"/ > 8. Add another Label control that displays the literal text Review Date:, followed by a binding to the formatted review date column.

<mx:Label text="Review Date: {simpleDate.format(data.review_date)}"/>

Using the item renderer component


9. Return to DataGrid_wt5.mxml. 10. Set the width of the DataGrid to 35% to accommodate the data that will be displayed in it. 11. Locate the DataGridColumn tag that displays the rating information. Add an itemRenderer property set equal to the component you just built, RatingDetail. <mx:DataGridColumn dataField="rating" headerText="Rating Info" itemRenderr="RatingDetail" /> Note: If the itemRenderer was stored in a folder, for example, itemRenderers, you would access the itemRenderer as follows: itemRenderer="itemRenderers.RatingDetail ". 12. Run the application. You should see in the second column the data displayed from the item renderer.

Pgina 256 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Using the TileList and HorizontalList


TileList displays items in a tile, and HorizontalList displays items in a single row Both controls use a dataProvider to supply data like the DataGrid

Using item renderers


Can use item renderers with TileList and HorizontalList like you did with DataGrid <mx:HorizontalList dataProvider="{listData}" itemRenderer="Thumbnail"/> Example Thumbnail.mxml <?xml version="1.0" encoding="utf-8"?> <mx:VBox xmlns:mx="http://www.adobe.com/2006/ mxml"> <mx:Image source="assets/{data.photo}"/> <mx:Label text="{data.food_name}"/> </mx:VBox>

Walkthrough 6: Displaying data with a TileList and HorizontalList


In this walkthrough, you will perform the following tasks: Use both a TileList and HorizontalList to display items Use an item renderer

Steps
1. 2. 3. Open the file assets/photo.xml to see the XML data you will work with in this walkthrough. Open the DataGrid_wt6.mxml file from the src folder at the root of the project. Run the application. You should see the data is successfully retrieved and displayed in the DataGrid.

Note: The DataGrid is used just so you can confirm the data is retrieved and see the names of the fields being used.

Using the TileList


4. Just below the DataGrid, insert a TileList component with the following properties and corresponding values. o dataProvider : {photoColl} o itemRenderer : itemRenderers.Thumbnail o width : 680 o rowHeight : 170 o columnwidth : 220

Pgina 257 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Creating the item renderer


5. 6. Right-click on the itemRenderers folder and select New > MXML Component. Enter the following values. o File Name: Thumbnail. mxml o Base Component: VBox o Width: Remove value o Height: Remove value Click Finish. Add the following properties and values to the VBox container to adjust the layout of the contents in the item renderer. o horizontalAlign : center o verticalAlign : middle Insert an Image control to display the current photo, which is stored in the assets folder.

7. 8.

9.

<mx:Image source="assets/{data.photo} "/> 10. Below the image use a Label control to display the food_name value. 11. Your item renderer should appear as follows. <?xml version="1.0" encoding="utf-8 "?> <mx:VBox xmlns:mx ="http://www.adobe.com/2006/mxml" horizontalAlign="center" verticalAlign="middle"> <mx:Image source="assets/{data.photo)"/> <mx:Label text="(data.food_name}"/> </mx:VBox>

Testing the application


12. Return to DataGrid_wt6.mxml and run the application. You should see the food pictures and associated name displayed in a tile. 13. Copy the entire TileList tag and paste it below itself. 14. Change TileList to HorizontalList. Also remove the width property and change the rowHeight value from 170 to 190. <mx:HorizontalList dataProvider="{photoColl)" itemRenderer="itemRenderers.Thumbnail" rowHeight="190" columnWidth="220"/> I

15. Run the application. You should now see both the TileList and HorizontalList displaying the food items.

Pgina 258 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Using events and selected items with list-based components


List-based components include DataGrid, TileList and HorizontalList When the user makes a selection in a list-based component, the change event is broadcast The item selected is available in the selectedItem property, datatyped as Object, which is a reference to the item in the dataProvider o If allowMultipleSelection is set to true, use selectedItems property, which is an array of the referenced items in the dataProvider o The index of the item selected is also available in the selectedIndex property, datatyped as int, and is the index in the dataProvider of the selected item If allowMultipleSelection is set to true, use selectedIndices property, which is an array of the indices of the referenced items in the dataProvider

Walkthrough 7: Using a change event on the TileList


In this walkthrough, you will perform the following tasks: Add a change event to the TileList Handle the event and use the selectedItem property to retrieve data

Steps
1. Open the DataGrid_wt7.mxml file from the src folder at the root of the project.

Adding the change event


2. Add a Change event to the TileList and have it call a function named tileChanged and pass the event object as a parameter.

change="tileChanged(event)"

Handling the event


3. 4. At the bottom of the Script block, add a private function named tileChanged, datatyped as void. The function should accept one parameter named event, datatyped as Event. In the function, assign the selected item from the TileList named foodTile to the text property of the Label control named foodName.

foodName.text =foodTile.selectedItem.food_name; 5. 6. Run the application. You should see when you click an item in the TileList, the name of the food appears above the TileList. Alter the code in the function so you use the event object to accomplish the same task of filling the Label control. Use the selected item of target object.

foodName.text = event.target.selectedItem.food_name; 7. Run the application. You should see the same behavior as before.

Pgina 259 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Summary
The DataGrid control is a list that can show formatted columns of data that users can edit o Provide data via a dataProvider o A common datatype for the dataProvider is an ArrayCollection Monitors data for changes and updated bindings Rich set of manipulation tools like filtering and sorting Columns of the DataGrid can be customized using the columns property, which contains an array of DataGridColumn objects o Determines which columns of data are displayed and their order Items in a DataGridColumn can be formatted using a labelFunction o Two parameters in the labelFunction An Object, traditionally named item, that holds the data passed from the DataGrid for that particular row A DataGridColumn object named after the column you are formatting o The function returns a formatted string The DataGrid has a default item renderer to display a single text string o to display anything else, must use a item renderer or item editor Item renderer displays data, while item editor displays and returns data o Using the rendererIsEditor property, an item renderer can also return data Item renderer used all the time, while item editor only when editing an item Three types of item renderers and item editors o Drop-in: Specify a control itemEditor="mx.controls.NumericStepper" o Inline: Give more control <mx:itemEditor> <mx:Component> <mx:NumericStepper minimum="1" maximum="5"/> </mx:Component> </mx:itemEditor> Component: Separate component built and used Access object in the component using the data variable Can also use item renderers with TileList and HorizontalList When a user clicks an item in a list-based component, a change event is broadcast Retrieve data using the selectedItem property in a list-based component o

Review
1. Name two advantages of using the ArrayCollection class as a dataProvider for list-based controls. 2. What property of the DataGridColumn class is used to tie it to specific data? 3. How many parameters must be accepted when writing a labelFunction, and what are their datatypes? 4. What is the difference between an item renderer and an item editor? 5. Name the three types of item renderers and item editors. 6. In a component item renderer, what variable contains the object to be displayed? 7. What advantage does the TileList have over the Tile/Repeater combination when it concerns large data sets? 8. What event is broadcast when a user makes a selection in a list-based component?

Pgina 260 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Lab 3
Objectives
In this lab, you will perform the following tasks: Retrieve remote data and create an ArrayCollection of Photo objects with that data Display images dynamically using a TileList from an array of Photo objects Display a clicked image in a view state Dispatch a custom event containing Photo object data Display purchased photos in a shopping cart

Part 1: Retrieving remote data and creating a data structure


In this part of the lab, you will perform the following tasks: Retrieve remote data Create a Photo value object Convert retrieved data into an array of Photo objects

Steps
Import the Lab3 Project
1. 2. Select File > Import > Flex Project. Import project from Archive File. o Browse to: <installDirectory>/adobeTraining/f3rca/ Lab3Project.zip o Click Open o Click Finish Close all unrelated projects. Open assets/photos.xml. This is the data you will be retrieving for use in the application. Examine the structure of the data then close the file. Open FStop.mxml.

3. 4. 5.

Retrieve remote data


6. Below the Style block, insert an HTTPService tag. Add the following properties and event. o o o 7. id: photosIn url: assets/photos.xml result: photosInHandler(event)

Add a creationComplete event to the Application tag and invoke a function named initApp.

creationComplete="initApp( )" 8. Below the Style block and above the HTTPService tag, insert a Script block. 9. In the Script block, create a private function named initApp, datatyped as void. 10. In the new function, invoke the send method of the photosIn HTTPService object.

Pgina 261 de 274

ADOBE FLEX 3 Developing Rich Client Applications photosIn.send();

11. In the Script block just above the existing function, create a private function named photosInHandler. The function should be datatyped as void and accept a parameter named event datatyped as ResultEvent. 12. If Flex Builder did not automatically import it at the top of the Script block, import the class mx.rpc.events.ResultEvent. 13. Place a breakpoint on the closing brace of the event handler function. 14. Debug the application and be sure the data is being correctly retrieved by examining the handlers event object.

Figure 1: HTTPService data

15. Terminate the debugging session and remove the breakpoint.

Create the Photo value object


16. Right click on the src folder within the Lab3 project and create a new folder named valueObjects. Note: You will create a number of ActionScript classes in this lab. You can have Flex Builder create the costructor by checking the Generate constructor from superclass option, or write the constructors yourself. 17. 18. 19. 20. 21. Right click on the valueObjects folder and select New > ActionScript Class. Be sure the package name is valueObjects. Set the Name of the class to be Photo. Click Finish. Mark the entire class as Bindable, which makes all the class' public variables bindable.

package valueObjects { [Bindable] public class Photo { } }

Pgina 262 de 274

ADOBE FLEX 3 Developing Rich Client Applications 22. Within the class, create the following public properties with the indicated datatype. o o o o filename:String photographer:String desc:String category:String

public var filename:String; public var photographer:String; public var desc:String; public var category:String; 23. After the properties, create an empty constructor for the class. public function Photo() { } 24. Be sure your Photo value object ActionScript class appears as follows. package valueObjects { [Bindable] public class Photo { public var filename:String; public var photographer:String; public var desc:String; public var category:String; public function Photo() { } } } 25. Return to FStop.mxml. 26. At the top of the Script block import the new class. import valueObjects.Photo;

Populate an Array-Collection with Photo objects


27. Import the mx.collections.ArrayCollection class. 28. In the Script block below any existing import statement, create a private, Bindable variable named photoData datatyped as ArrayCollection. Set the variable equal to a new instance of the ArrayCollection. [Bindable] private var photoData:ArrayCollection= new ArrayCollection();

Pgina 263 de 274

ADOBE FLEX 3 Developing Rich Client Applications

29. In the photosInHandler method,use the var statement to create a variable local to the function named photoRaw datatyped as ArrayCollection. Set the variable equal to the data retrieved by the HTTPService object. Remember the repeating node in the XML result data is named image. var photoRaw:ArrayCollection = event.result.photos.image; 30. Create a for loop with an iterant named i which is local to the function, datatyped as int, and initialized to 0 (zero). The loop should continue while the value of i is less than the length of the photoRaw array. Increment i by 1 for each iteration. for(var i:int=0;i<photoRaw.length;i++) { } 31. In the loop, create a variable local to the function named tempPhoto datatyped as Photo and set it equal to a new Photo instance. var tempPhoto:Photo = new Photo(); 32. Next in the loop, create a variable local to the function named photoFromAC and datatype it as Object. Using the getItemAt() method, retrieve the ith item from the photoRaw ArrayCollection and assign it to photoFromAC. var photoFromAC:Object=photoRaw.getItemAt(i); 33. Next in the loop, assign the filename, photographer, desc and category properties of the tempPhoto object the corresponding values from the photoFromAC object. tempPhoto.filename =photoFromAC.filename; tempPhoto.photographer = photoFromAC.photographer; tempPhoto.desc = photoFromAC.desc; tempPhoto.category=photoFromAC.category; 34. As the last line of code in the loop, use the addItem( ) method to add the tempPhoto Photo object to the photoData ArrayCollection. 35. Check to be sure your function appears as follows. private function photosInHandler(event:ResultEvent):void { var photoRaw:ArrayCollection= event.result.photos.image; for(var i:int=0;i<photoRaw.length;i ++) { var tempPhoto:Photo=new Photo( ); var photoFromAC:Object= photoRaw.getItemAt(i); tempPhoto.filename=photoFromAC.filename; tempPhoto.photographer= photoFromAC.photographer; tempPhoto.desc=photoFromAC.desc; tempPhoto.category=photoFromAC.category; photoData.addItem(tempPhoto) ; } }

Pgina 264 de 274

ADOBE FLEX 3 Developing Rich Client Applications 36. Place a breakpoint on the closing brace of the function. 37. Debug the application and locate the photoData variable inside the this object. Be sure the data is being correctly converted into an ArrayCollection of Photo objects.

Figure 2: An ArrayCollection containing Photo objects

38. Terminate the debugging session and remove the breakpoint.

Part 2: Displaying dynamic images in the gallery


In this part of the lab, you will perform the following tasks: Create a custom component itemRenderer to display image data Allow access to the newly created itemRenderer using a namespace declaration Create a Bindable property to pass retrieved data to the Gallery component Remove hardcoded images Display images in a TileList container component Pass data to the Gallery component using databinding

Steps
Create an itemRenderer component to display image data
1. Right click on the views folder and select New > MXML Component. o o 2. 3. 4. Filename: DisplayImage.mxml Based on: Image

Click Finish. Convert the Image tag set to a single tag. Add a source property to the Image tag. Set the value to retrieve an image from the assets/gallery/ directory and bind the image name. Add _sm. jpg to the end of the filename outside the binding. The filename property itself is available in the data property (where data is passed to an itemRenderer).

Pgina 265 de 274

ADOBE FLEX 3 Developing Rich Client Applications

5.

Check to be sure your itemRenderer appears as follows.

<?xml version="1.0" encoding="utf-8"?> <mx:Image xmlns:mx="http://www.adobe.com/2006/mxml" source="assets/gallery/{data.filename}_sm.jpg" /> Note: You could have also used a binding around the entire string and use string concatenation, as shown here: source="{'assets/gallery/ '+data.filename+'_sm.jpg'}". Note: You could have used the Image tag directly as a drop-in item renderer instead of creating the custom itemRenderer, but the itemRenderer will be needed later.

Enable access to the itemRenderer


6. 7. Open views/Gallery.mxml. Add a new namespace declaration to the VBox component to allow access to the itemRenderer you just created. Use the letter v as the prefix.

xmlns:v="views.*"

Create a property to pass retrieved data


8. Just below the VBox tag insert a Script block. 9. In the Script block, import the mx.collections.ArrayCollection class. 10. Create a Bindable, public variable named photoData datatyped as ArrayCollection. [Bindable] public var photoData:ArrayCollection;

Remove hardcoded images


11. Locate the Tile container (use the Flex Builder Outline view for help). 12. Remove the Tile container and all Image tags that are inside it.

Display images using a TileList control


13. Insert a TileList tag set and set its id property to thumbnails. 14. Bind its dataProvider property to the photoData ArrayCollection using curly brace syntax. 15. Add the following properties and associated values to style the look of the TileList. o o o o o o o o o backgroundColor: #000000 backgroundAlpha: 0 columnWidth: 120 rowHeight: 110 width:515 height: 430 rollOverColor: #63769E borderThickness: 0 itemRenderer: views.Display Image

Pgina 266 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Pass data to the Gallery component


16. Open FStop.mxml. 17. Locate the instantiation of the Gallery component (use the Flex Builder Outline view for help). 18. Add a photoData property to the Gallery component and bind it to the photoData ArrayCollection using curly brace syntax. <v:Gallery id="gallery" label="Gallery" photoData="{photoData} "/> 19. Run the FStop.mxml application. View the Gallery. You should see that when you click on the Gallery link at the top of Application, the photos, whose information was dynamically retrieved, are displayed in the TileList.

Part 3: Displaying a clicked image in the view state


In this part of the lab, you will perform the following tasks: Modify state children for dynamic images Display the photo data when an image is clicked

Steps
1. Open Gallery.mxml from the views folder.

Modify state children for dynamic images


2. 3. 4. Locate the Image tag in the detailsState and give it an id property with a value set to photoInState. Remove the source property from the Image tag. Check that your Image tag appears as follows.

<mx:Image id="photoInState" x="55" y="15" width="400"/> 5. 6. 7. Locate the Text tag in the details state that displays the photographer name and give it an id property set to photographerText. Remove the text property from the photographerText tag. Check to be sure your photographerText tag appears as follows.

<mx:Text id ="photographerText" x="65" y="330" width="367" height="18" fontWeight="bold" color="#F8E5BB" /> 8. 9. Locate the Text tag in the details state that displays the description of the photo and give it an id property set to descText. Remove the text property from the descText tag.

Pgina 267 de 274

ADOBE FLEX 3 Developing Rich Client Applications

10. Check to be sure your descText tag appears as follows. <mx:Text id="descText" x="65" y="350" width="367" height="36" color="#F8E5BB" />

Display the photo data when clicked


11. Add a change event to the TileList and set the event handler to the displayDetails function passing an event object as the only parameter. change="displayDetails(event)" 12. In the Script block, create a Bindable, private variable named selectedPhoto and datatype it as Photo. 13. Check tabe sure Flex Builder imported the Photo class for you. Look in the Script block to be sure the class valueObjects. Photo was imported. If not, import it. 14. At the end of the Script block, insert a private function named displayDetails that returns void. 15. The displayDetails function should accept a parameter named event datatyped as Event. private function displayDetails(event:Event):void { } 16. As the first line of code in the displayDetails function, change the currentState of the view state to details. currentState=details; 17. Assign the selectedPhoto variable the value of the selectedItem property of the event.target object, and cast to a Photo instance. selectedPhoto=event.target.selectedltem as Photo; 18. Load the new image into the state using the load ( ) method of the photoInState Image class. You will need to specify the directory for the images, assets/ gallery/, concatenate the selectedPhoto.filename and the jpg extension. photoInState.load('assets/gallery/' + selectedPhoto.filename +'.jpg'); 19. Assign the photographer property of selectedPhoto to photographerText.text to display the photographer name in the Text field. photographerText.text = selectedPhoto.photographer; 20. Assign selectedPhoto.desc to descText.text to display the description in the Text field. descText.text=selectedPhoto.desc;

Pgina 268 de 274

ADOBE FLEX 3 Developing Rich Client Applications 21. Run the FStop.mxml application. You should see that when you click on a thumbnail in the Gallery the full size image appears in the details view state.

Part 4: Passing photo information for a purchased photo


In this part of the lab, you will perform the following tasks: Create a custom event class Implement the custom event Add a purchase photo button Dispatch the custom event object containing the photo information Handle the custom event

Steps
Create a custom event class
1. 2. Right click on the src folder within the Lab3 project and create a new folder named events. Right click on the events folder and select New > ActionScript Class. o Package: events o Name: PhotoEvent o Superclass: Event Click Finish. Below the existing import statement also import the valueObjects.Photo class. In the class definition, create a public variable named selectedPhoto datatyped as Photo.

3. 4. 5.

public var selectedPhoto:Photo; 6. Below the variable declaration, create the class constructor. It should accept two parameters, the first named type datatyped as String and the second named selectedPhoto datatyped as Photo.

public function PhotoEvent(type:String, selectedPhoto:Photo) { } 7. In the constructor, call the Events constructor (the parent of this class) using the super() method passing the type parameter.

super(type); 8. Next assign the Selectedphoto parameter to the class' selectedPhoto property using the this keyword.

this.selectedPhoto=selectedPhoto; 9. Create another public function that will override the clone method and returns an Event class.

Pgina 269 de 274

ADOBE FLEX 3 Developing Rich Client Applications

override public function clone(): Event { } 10. In the clone function, return a new instance of the PhotoEvent custom event class, passing type and selectedPhoto as parameters. return new PhotoEvent(type.selectedPhoto); 11. Your package should appear as follows. package events { import flash.events.Event; import valueObjects.Photo; public class PhotoEvent extends Event { public var selectedPhoto:Photo; public function PhotoEvent(type:String,selectedPhoto:Photo) { super(type); this.selectedPhoto = selectedPhoto; } override public function clone():Event { return new PhotoEvent(type, selectedPhoto); } } }

Define the custom event


12. Open Gallery.mxml from the views folder. 13. At the top of the Script block import the events.PhotoEvent class. 14. Above the Script block, using the Metadata directive, define an Event. Use photoSelected as the name for the event, and use the events. PhotoEvent class for the type. <mx:Metadata > [Event(name="photoSelected", type ="events.PhotoEvent")] </mx:Metadata> Note: The Metadata tag informs the compiler that the class may dispatch an event with the given name and type.

Add a purchase photo button


15. In the details view State just below the existing Button, add another Button for photo purchase that calls a purchasePhoto() function on the click event and has other properties as shown.

Pgina 270 de 274

ADOBE FLEX 3 Developing Rich Client Applications <mx:Button x="200" y="400" fillAlphas=" [1, .8]" fillColors= "[#F8E5BB, #F8E5BB]" label="purchase photo" click="purchasePhoto()" />

Dispatch the custom event object


16. At the end of the Script block, create a private function named purchasePhoto that returns void. 17. In the purchasePhoto function, create local variable named eventObj datatyped as PhotoEvent equal to an instantiation of the PhotoEvent class. Pass the String photoSelected and selectedPhoto as parameters. var eventObj:PhotoEvent = new PhotoEvent("photoSelected", selectedPhoto); 18. As the last line of code in the function, use the dispatchEvent() method to dispatch the eventObj object. 19. The code should appear as follows. private function purchasePhoto():void { var eventObj:PhotoEvent=new PhotoEvent("photoSelected", selectedPhoto); dispatchEvent(eventObj); }

Handle the custom event


20. 21. 22. 23. Open FStop.mxml. At the top of the Script block, import the events. PhotoEvent class. Locate the instantiation of the Gallery component (use the Flex Builder Outline view for help). In the Gallery component, add the photoSelected custom event and call the photoSelectedHandler passing the event object as a parameter.

photoSelected = "photoSelectedHandler(event)" 24. At the end of the Script block, create a private function named photoSelectedHandler and returns void. The photoSelectedHandler should accept one parameter named event datatyped as PhotoEvent. 25. Place a breakpoint on the closing brace of the photoSelectedHandler function. 26. Debug the application and click on the Gallery menu item. Click on an image and then click on the purchase photo button. 27. In the debugger be sure you can see the purchased photo

Figure 3: The selected photo from the custom event

Pgina 271 de 274

ADOBE FLEX 3 Developing Rich Client Applications

28. Terminate the debugging session and remove the breakpoint.

Part 5: Displaying purchased photos in the shopping cart


In this part of the lab, you will perform the following tasks: Pass purchased photos to the shopping cart Bind purchased photos to the DataGrid

Steps
1. Open FStop.mxml from the src folder at the root of the project.

Pass purchased photos to the shopping cart


2. In the Script block below the existing variable declaration, create a Bindable, private variable named purchasedPhotos datatyped as ArrayCollection and instantiate it.

[Bindable] private var purchasedPhotos:ArrayCollection= new ArrayCollection(); 3. In the photoSelectedHandler() function, use the addIterm() method to add the selectedPhoto contained in the event object to the purchasedPhotos ArrayCollection.

private function photoSelectedHandler(event:PhotoEvent): void { purchasedPhotos.addItem(event.selectedPhoto); } 4. Locate the instantiation of the ShoppingCart component (use the Flex Builder Outline view to do this) and bind the components purchasedPhotos property to the purchasedPhotos variable.

<v:ShoppingCart x="626" y="118" purchasedPhotos="{purchasedPhotos}" /> Note: This property does not yet exist in the ShoppingCart component. It will be created next.

Bind purchased photos to the DataGrid


5. 6. 7. 8. 9. Open ShoppingCart.mxml from the views folder. Just below the starting Canvas tag add a Script block. Within the Script block, import the mx.collections.ArrayColection class. Create a Bindable, public variable named purchasedPhotos datatyped as ArrayCollection. The Script block should appear as follows.

Pgina 272 de 274

ADOBE FLEX 3 Developing Rich Client Applications

<mx:Script> <![CDATA[ import mx.collections.ArrayCollection; [Bindable] public var purchasedPhotos:ArrayCollection; ]]> </mx:Script>

10. Locate the DataGrid (in the expandedCart state) and bind the dataProvider property to the purchasedPhotos ArrayCollection. <mx:DataGrid x="10" y="60" height="340" dataProvider="{purchasedPhotos}" > 11. Alter the first DataGridColumn to display the filename using the dataField property and set the headerText property value to Picture. Add the width property and set it to 60. 12. Alter the second DataGridColumn to display the photographer using the dataField property and set the headerText property to Information. Add a width property and set it to 100. <mx:DataGrid x="10" y="60" height="340" dataProvider="{purchasedPhotos} "> <mx:columns> <mx:DataGridColumn headerText="Picture" dataField="filename" width="60"/> <mx:DataGridColumn headerText="Information" dataField="photographer" width="100"/> </mx:columns> </mx:DataGrid> 13. Run the FStop.mxml application. Click the Gallery menu item. Click a thumbnail, and then click the purchase photo button. Expand the shopping cart. You should see that the photos are added to the shopping cart. At this point multiple purchases of the same photo appear multiple times in the cart.

Implement the items in cart counter


14. In ShoppingCart.mxml, locate the Label in the Panel (use the Flex Builder Outline view to help). 15. Replace the 0 (zero) currently being displayed in the text property of the Label with a binding to the length property of the purchasedPhotosArrayCollection . Text="You have {purchasedPhotos.length} item(s) in your cart. " 16. Run the FStop.mxml application. Purchase multiple photos. You should see that the counter increments correctly.

Pgina 273 de 274

ADOBE FLEX 3 Developing Rich Client Applications

Add a itemRenderer to the DataGrid


17. 18. 19. 20. 21. 22. 23. Locate the second DataGridColumn (use the Flex Builder Outline view to help). Remove the dataField property. Change the DataGridColumn from a single tag to a tag set. Nest an itemRenderer tag set within the DataGridColumn. Nest a Component tag set within the itemRenderer. Nest a VBox tag set in the Component. Add a Label component and bind the text property to the value of the photographer. Do the same with the category. Remember the item information in a itemRenderer is accessible through the data property. The code should appear as follows.

<mx:DataGridColumn headerText="Information" width="100"> <mx:itemRenderer> <mx:Component> <mx:VBox> <mx:Label text="{data.photographer}"/> <mx:Label text="{data.category}"/> </mx:VBox> </mx:Component> </mx:itemRenderer> </mx:DataGridColumn> 24. Run the FStop.mxml application. Click the Gallery menu item. Click a thumbnail, and then click the purchase photo button. Expand the shopping cart. You should see that the Information column in the DataGrid now contains both the photographer name and category.

Pgina 274 de 274

You might also like