Developing Rich Client Applications
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
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
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
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
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
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
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:
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
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
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
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%
Pgina 12 de 274
Pgina 13 de 274
Pgina 14 de 274
Pgina 15 de 274
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
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
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
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
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
Pgina 20 de 274
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
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
Pgina 20 de 274
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
Pgina 21 de 274
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
Pgina 22 de 274
Pgina 23 de 274
Pgina 24 de 274
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
Pgina 25 de 274
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
</mx:Application>
Pgina 26 de 274
Note: If there is not a check mark, select Build Automatically. If there is already a checkmark, do nothing.
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
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:
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.
Note: You can also maximize and restore views in this way.
Pgina 28 de 274
Manipulating views
27. Close the Navigator view by clicking on the X on the tab:
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.
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
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
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
Debugging an application
Start by using the Debug button Click down arrow beside the debug button Select application from drop-down list
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
Pgina 32 de 274
ADOBE FLEX 3 Developing Rich Client Applications Use the Variables view to see all variables for the application
BE SURE to stop the debugging session before continuing other work Browser opened for the debugging session will automatically close
Pgina 33 de 274
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.
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.
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:
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
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
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
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
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.
Pgina 38 de 274
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
<?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
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!"/>
Pgina 41 de 274
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.
Pgina 42 de 274
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)
Pgina 43 de 274
Pgina 44 de 274
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
Pgina 46 de 274
Pgina 47 de 274
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
The following MXML snippet shows how you would lay out these three controls using the VBox layout
HBox
The HBox layout displays controls horizontally, as in the following image
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
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
This x/y positioning is only valid for components on the Canvas, not for components inside child containers
Pgina 49 de 274
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.
4.
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
includes a panel title, a title bar, a status message and a content area for its children
Pgina 51 de 274
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
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.
<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.
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
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.
Pgina 55 de 274
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"
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
Pgina 57 de 274
Steps
1. Open the Fundamentals_wt6.mxml file from the src folder at the root of the project.
<mx:Label 4.
Run the application. You should see the Label containing text, and the width displayed below.
<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
Pgina 59 de 274
<comp:Component1/>
Pgina 60 de 274
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***"/>
Pgina 61 de 274
Pgina 62 de 274
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;
Pgina 63 de 274
1.
comp refers to the namespace for all of the files in the components directory.
2.
3.
4.
5.
6.
7.
Steps
1. Open the PropMethod.mxml file in the components folder within the src folder at the root of the project.
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.
Pgina 64 de 274
xmlns:comp="components.*"
8. Instantiate the component via MXML and initialize the property just created to your name.
<mx:Label text ="{ myComp.prop1} "/> 17. Run the application. You should see your name is now displayed twice.
Pgina 65 de 274
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
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.
5.
6.
Pgina 67 de 274
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
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
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
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.
Pgina 70 de 274
<mx:Button id="myButton" label="Click Me" click="myLabel.text='You clicked'"/> <mx:Label id="myLabel" text="Click {myButton.label}"/>
Pgina 71 de 274
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.
<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.
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
Pgina 73 de 274
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.
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.
<mx:Script source="asHandlers.as"/>
Pgina 74 de 274
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.
Pgina 75 de 274
Pgina 76 de 274
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
Pgina 78 de 274
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.
Note: You can do this by double-clicking in the editors left margin next to I line of code.
5.
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.
Tip: Remember you can double click the Variables view tab to open the view full screen.
Pgina 79 de 274
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.
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.
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.
Pgina 80 de 274
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
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);
Pgina 82 de 274
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.
4.
5.
6. Why should you use the strictest class possible when datatyping a parameter passed to an event handler function?
Pgina 83 de 274
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
vertical Panel requires setting the layout property to absolute, by default layout is vertical Canvas always uses absolute positioning (it has no layout property)
Figure 1: The Canvas container's origin point is the upper left corner
Pgina 85 de 274
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
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
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.
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.
16. Run the application. You should see the seating chart with the text overlay.
17. Switch to Source mode and review the code with your instructor.
Pgina 88 de 274
Figure 5: if a component is set to a percentage width, it will resize to ensure that the anchor rules stay true
Pgina 89 de 274
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
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.
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.
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.
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.
Pgina 92 de 274
12. Make sure the Text control is still selected and set the 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
Pgina 94 de 274
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.
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>
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
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.
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.
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.
Pgina 98 de 274
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.
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
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.
4.
5.
6.
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.
6.
Click Finish. You should see the new FStop.mxml page appear in the Flex Builder editor within the src folder.
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>
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 >
25. Run the application. You should see the Home components content appear in the main application display.
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.
5. 6. 7.
8.
9.
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.
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.
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.
21. Be sure your FormItem containing the Button appears as shown here.
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.
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.
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>
Note: You will get an error message if you click on any of the thumbnail photos. The application will be completed in later labs.
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
Figure 1: Flash an Flex allow you to create dynamic applications that can change their presentation layouts without refreshing the browser windows
Example #2
3.
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)
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.
13. Select the LinkButton control in the forms state and delete it. The LinkButton control still exists in the Base state.
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.
<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
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.
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 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.
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.
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
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>
<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>
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.
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.
Figure 11: Custom components can define view states which are then accessible from the main application
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
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.
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.
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.
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.
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
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
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>
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
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>
Figure 3: Navigating the ViewStack container with TabBar navigator and custom Button controls
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
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
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
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.
<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.
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.
<mx:TabBar dataProvider="{cafeTownsendContent} " /> <mx:Button label="> 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.
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
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
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.
Figure 3: The ToggleButtonBar control holds buttons that can maintain state
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)
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.
<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.
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?
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
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
Styles are defined on components You can customize these styles (and add your own)
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)
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);
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
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
<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" />
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
<mx:Style> .textBackground { backgroundImage: Embed("images/purpleGradient.gif"); } </mx:Style> <mx:HBox> <mx:TextArea width="200" height="200" styleName="textBackground" /> </mx:HBox>
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')" />
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
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.
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.
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.
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.
Effect AnimateProperty
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
<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
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
<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"
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.
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.
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>
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>
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
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.
<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.
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.
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.
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
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.
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>
28. Run the application. You should see the ShoppingCart component content on the right of the screen, below the header.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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
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>
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
ADOBE FLEX 3 Developing Rich Client Applications Code example package food.maindish { public class Pasta { } }
Note: The Flex Builder project name is supplies, so it is not included in the class path
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
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
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
} } }
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() { } } }
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.
5.
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( ) { } } }
13. Run the application. You should see the three property values displayed in the Label controls.
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
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
Steps
1. Open RestaurantProduct2.as in the valueObjects folder.
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.
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.
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()}"/>
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.
<mx:Label text="{garlic.prodInfo()}"/> 6. Run the application. You should see the product name and description displayed in the Label.
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
<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?
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
A much cleaner approach would be to let the component dispatch an event, just like a Button dispatches a click event
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.
<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.
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>
ADOBE FLEX 3 Developing Rich Client Applications ]]> </mx:Script> <local:MyComponent myCustomEvent="customEventHandler()"/> <mx:Label id="theLabel"/> </mx:Application>
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.
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); }
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.
Adding properties
You can now add properties to hold the data that you want to send with the custom event public var custEvProperty:String;
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.
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
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.
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); } } }
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.
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
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
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>
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.
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.
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.
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.
8.
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);
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); }
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
Figure 7: Error displayed when the validator does not pass validation
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.
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.
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*);
6.
Run the application and test validation. You should see that validation triggered upon the button click, and the error message is displayed.
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?
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
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
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
arrayCollectionInstance.getItemAt(n)
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
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.
<mx:DataGrid dataProvider="{sanData.lastResult.sandwichMenu.sandwich}" /> 10. Run the application. You will see the data displayed in the DataGrid
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.
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.
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.
Steps
1. Open the HTTPService_wt2.mxml file in the src folder at the root of the project.
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.
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.
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
These messages are for development. More robust error handling would need to be implemented for production applications
Steps
1. 2. Open HTTPService_wt3.mxml. Run the application. You should see an unhandled runtime error.
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.
8.
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.
Example to allow access from any domain <cross-domain-policy> <allow-access-from domain="*"/> </cross-domain-policy>
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.
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.
<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();"/>
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.
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.
<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.
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.
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.
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?
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
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" . . . />
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
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
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.
5.
<mx:DataGrid dataProvider="{restaurants}"> <mx:columns> <mx:DataGridColumn dataField="style" headerText="Style" /> <mx:DataGridColumn dataField="number" headerText="Available" /> </mx:columns> </mx:DataGrid>
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.
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" />
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.
private function dateFormatFunc(item:Object, review_date:DataGridColumn):String { return myDate.format(item.review_date) + ": "+ item.rating; } ... <mx:DateFormatter id="myDate" formatString="DDMMM- YY"/>
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.
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. "
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].
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.
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
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
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
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
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.
When used with a DataGrid, must set the DataGrid s editable property to true
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.
<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.
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.
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
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.
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"
Steps
1. Open the DataGrid_wt5.mxml file from the src folder at the root of the project
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.
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.
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>
15. Run the application. You should now see both the TileList and HorizontalList displaying the food items.
Steps
1. Open the DataGrid_wt7.mxml file from the src folder at the root of the project.
change="tileChanged(event)"
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.
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?
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
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.
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.
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.
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;
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) ; } }
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.
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).
5.
<?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.
xmlns:v="views.*"
Steps
1. Open Gallery.mxml from the views folder.
<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.
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" />
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.
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.
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); } } }
ADOBE FLEX 3 Developing Rich Client Applications <mx:Button x="200" y="400" fillAlphas=" [1, .8]" fillColors= "[#F8E5BB, #F8E5BB]" label="purchase photo" click="purchasePhoto()" />
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
Steps
1. Open FStop.mxml from the src folder at the root of the project.
[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.
<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.
<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.