Learning Flex 4 – Spark Components and Skinning Basics

One of the key changes to Flex moving to version 4 is the introduction of the Spark component set.

The components in Flex 3 (Button, TextInput etc) were known under the code name Halo and they’re still available in Flex 4. These components are distinguished by the mx namespace prefix you are used to. The new Spark components have an s prefix and require the addition of a new namespace definition – xmlns:s="library://ns.adobe.com/flex/spark" (The mx namespace definition also changes to  xmlns:mx="library://ns.adobe.com/flex/halo").

There are Spark equivalents of most but not all mx or Halo components (DataGrid, AdvancedDataGrid and Tree are some of the currently missing).

The key difference in the component sets is their construction. Halo components contain everything required for that object including styling, behavior and layout. Spark components on the other hand, separate out the behavior of a component from the display aspects. The information corresponding to component display is kept in a separate skin class.

The upshot of this change is that the look and feel of an application can be separated from it’s behavior and more readily changed. With the introduction of the Catalyst tool in CS5, designers can deal with the display skins while developers deal with the underlying behavior.

You can specify the skin a component should use with:

  • CSS: S|Button {skinClass: ClassReference ("com.example.skins.MyButtonSkin");}
  • MXML: <s:Button skinClass="com.example.MyButtonSkin"/>
  • ActionScript: myButton.setStyle("skinClass",Class(MyButtonSkin);

The skin class is generally written in MXML and defines the states (with transitions) the skin reacts to, graphical elements and any component parts the skin is constructed from. The skin may also specify the HostComponent in a metadata tag. The HostComponent is the component class that will use the skin. This is useful for the skin to be able to gain a reference to properties of the component instance.

A skin class must declare state properties that are specified for it’s host component. For example, a Spark Button has states up, over, down and disabled so the skin must declare what it looks like for each of these states. The component will then set the relevant state at runtime.

Skin parts are sub components used to define a larger component – for example, a scrollbar has increment and decrement button parts together with a track and thumb part whereas a button just has a label.

The graphical elements of a skin are defined using a new graphics tag library cald FXG which includes graphics and text primitives including tags for creating basic shapes, fills, gradients and bitmaps. FXG is also used by Catalyst and other tools to transfer graphical data. The specification for FXG can be found here.

A great way to begin working with Skins is to modify the Adobe supplied skin class for a component. Flash Builder 4 has a workflow for creating skin classes that allows you to work from a supplied class. With FlashDevelop, you’ll have to go off and find the class for yourself and copy it in to your project under the name you want. You’ll find the skin class source files under your SDK install in the frameworks\projects\spark\src\spark\skins\spark directory.

For further detail on skinning Spark components, take a look at these Adobe articles.

Advertisements
Posted in Flex. 4 Comments »

Learning Flex – Lesson 16, part II Skinning Components

Each component has several “skins” to describe the look of that component in different situations. As an example, a Button has upSkin for it’s default appearance, overSkin for how it appears with the mouse pointer over it, downSkin for when it’s pressed and disabledSkin for when it’s disabled (it also has a corresponding set of 4 for when it’s selected). The available skins for a component are enumerated in the Adobe documentation.

There are three types of skins:

  • Graphical Skins – these are image files that define the appearance of the skin (jpeg, gif or png)
  • Programmable Skins – ActionScript or MXML classes that define a skin using the Flash Drawing API. A single class can define multiple skins.
  • Stateful Skins – programmatic skins that use view states where each state corresponds to a skin of the component.

Graphical Skins

These can be applied inline:

<mx:Button upSkin="@Embed('../assets/buttonUp.gif')"/>

within a Style tag:

<mx:Style>
Button{
overSkin: Embed ("../assets/buttonOver.gif");
}
</mx:Style>

and within ActionScript:

[Embed("../assets/buttonDown.gif")]
public var buttonDwnSkin:Class;


myButton.setStyle("downSkin" , buttonDwnSkin);

Programmatic Skins

You can create programmatic skins either in MXML or ActionScript and define a class per skin or a single class for multiple skins. Using the Flash Player drawing API allows you more flexibility in your design.

The first step is to choose the base class you want to extend for you skin. The main choices are:

  • ProgrammaticSkin – this implements the IFlexDisplayObject, ILayoutClient & IStyleable interfaces. It’s the the most lightweight super class for a skin.
  • Border – this extends ProgrammaticSkin and adds support for the borderMetrics property. This would be used to implement a skin with a border that does not require a background image.
  • RectangularBorder – this extends Border and adds support for the backgroundImage style.

The majority of the work for the class is in overriding the updateDisplayList() method. If you choose one of the border classes, you will also need to override the getter method for the borderMetrics property to return your values.

The name property will provide the current skin name to be rendered. Use graphics.clear() to remove any prior elements, a fill method (beginFill(), beginGradientFill() or beginShaderFill() ) to specify the fill that subsequent graphics calls will use, one or more of the draw methods followed by endFill() to see the graphics displayed.

To use a programmatic skin, you need to provide the created class name. To apply it inline:

<mx:Button overSkin="{MyComponents.MyButtonSkin}"/>

within a Style tag:

<mx:Style>
Button{
upSkin:ClassReference("MyComponents.MyButtonSkin");
}
</mx:Style>

and within ActionScript:

myButton.setStyle("upSkin",MyComponents.MyButtonSkin);

Stateful Skins

Flex components such as Button, Slider etc can use stateful skins. They have a style property that is defined for several skin states (for Button it’s skin, for Slider, thumbSkin). By defining a custom skin class based on UIComponent, you can define view states corresponding to some or all of the possible skins and specify graphics for them. This gives you the ability to use transitions to animate the state changes.

You use a stateful skin in the same way as a programmatic skin –  by assigning the class name to the relevant style property (skin for Button etc).

You can make your own custom style properties by making a call to getStyle() within updateDisplayList() and supplying the name of your style.  You should wrap this call with isValidStyleValue() to check if the property exists before you try to use it and declare a default value in the class constructor.

It puts the lotion on its skin…

If the previous post about wizards & skinning has you itching to try writing your own rather than just taking and modifying someone else’s, you should check outDan Orlando’s Blog specifically the post he wrote for IBM Developerworks on Flex and CSS. It’s a great introduction into styling your app. You should also consider playing with the Adobe Flex Style explorer which allows you to play with styling components graphically and provides you the resulting CSS.

Wizards & Skinning

Back when I was first looking at Flex, I knocked up a little prototype for work to show some people a possible solution to a problem they were having. They need to produce custom catalogs of products for clients that differ in the elements they require and the format of the file produced. Some may want XML, some fixed length fields, others delimited text (, | etc).

I wrote a wizard in Flex that would take you through the process of specifying a file and then use a Java method via BlazeDS to create the file (the Java code just constructed a demo file from the field data you provided for the prototype). In the end, it turned out that getting all the source data for the elements was the real sticking point so it never went any further.

I hadn’t done anything with it since but I started thinking about skinning apps (as a developer, I’m a terrible designer) and figured this wouldn’t be a bad app to try it on. If you go to Scale nine and check out the gallery, you’ll see a number of themes you can download for free. If you can’t find one you like, there should be enough there to show you how to modify one that’s close or write your own.

I downloaded the “Undefined” skin and dumped it all in my wizard project. The skin came with a main mxml file so it was pretty obvious to see how to use it in my own files.  All I had to do was use an mx:Style tag to import the css and specify the styleName property for my components.

I went from a screen that looked like this:

old wizard screen

to one that looked like this:

new wizard screen

While you might not like the look of either of them, you’ve got to admit, it’s pretty nice to be able to change the look of your app so easily.

The app itself makes use of states to change the layout of the screen and walk the user through the steps they have to take.  START is the first state and requests the customer id the catalog is for. There’s no back button in this state as we’ve got nothing to go back to. The next state is the one shown above, PICK_FIELDS. This displays the available fields in the left list from an ArrayCollection (fromAC) defined in the app and the right list is bound to another ArrayCollection (toAC). Drag/drop is enabled to allow the user to specifiy the fields they need and the order they want them in. The next state is SPEC_FIELDS, this contains text fields for a document header and footer (in the case of XML files) and a datagrid which has columns for the field name ( taken from toAC), max length, pad character, pre string and post string. This allows the user to specify the format of each of the elements they have selected. The results are stored in another ArrayCollection (fieldAC). The final state is GENFILE which in this case just displays some debug and removes the buttons but for a final version would display some messaging about the file created.

It’s worth noting also how the states use mx:SetEventHandler to change the behavior of the back and next buttons in the various states. Hopefully it’s fairly obvious what’s going on with that explanation and the source provided below and maybe it’ll provide you with some ideas for your own “wizard” style apps.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" borderColor="#B7BABC" themeColor="#9999CC" currentState="START">
<mx:Style source="/css/skinPreview.css/"/>
<mx:Script>
<![CDATA[

import mx.controls.DataGrid;
import mx.collections.ArrayCollection;

[Bindable]
public var toAC:ArrayCollection = new ArrayCollection();

[Bindable]
public var fromAC:ArrayCollection = new ArrayCollection([“Product Id”, “Price”, “Description”, “Long Description”, “UOM”, “ECO”, “Minority”]);

[Bindable]
public var fieldAC:ArrayCollection=new ArrayCollection();

private function next():void
{
if (currentState==”SPEC_FIELDS”)
{
currentState=”GENFILE”;
}else
{
currentState=(currentState==”START”) ? currentState=”PICK_FIELDS” : currentState=”SPEC_FIELDS”;
}
}

private function back():void
{
currentState=(currentState==”SPEC_FIELDS”) ? currentState=”PICK_FIELDS” : currentState=”START”;
}

private function drawDetails(event:Event):void
{
next();
var toArray:Array=toAC.toArray();
for(var i:String in toArray)
{
var field:FieldData=new FieldData();
field.name=toArray[i];
fieldAC.addItem(field);
}
}

private function wipeDetails(event:Event):void
{
fieldAC.removeAll();
back();
}

private function createFile(event:Event):void
{
next();
ro.createFile(custText.text,docHead.text,fieldAC.toArray(),docFoot.text);
}

]]>
</mx:Script>

<mx:RemoteObject id=”ro” destination=”cif-creator”/>

<mx:states>
<mx:State name=”START”>

<mx:AddChild relativeTo=”{changeBox}”>
<mx:HBox id=”custInput”>
<mx:Label id=”custLabel” text=”Customer Id” styleName=”myText”/>
<mx:TextInput id=”custText” />
</mx:HBox>
</mx:AddChild>

<mx:RemoveChild target=”{backBtn}” />

</mx:State>

<mx:State name=”PICK_FIELDS”>

<mx:AddChild relativeTo=”{changeBox}”>
<mx:HDividedBox id=”divBox” horizontalAlign=”center” horizontalGap=”10″ verticalAlign=”top” label=”Field Chooser” borderStyle=”inset” width=”100%”>
<mx:List id=”fromList” dataProvider=”{fromAC}” allowMultipleSelection=”true”
dragEnabled=”true” dropEnabled=”true”
dragMoveEnabled=”true” styleName=”myText” width=”50%” height=”100%” fontSize=”12″ backgroundColor=”#E2E2E2″/>
<mx:List id=”toList” dataProvider=”{toAC}” allowMultipleSelection=”true”
dragEnabled=”true” dropEnabled=”true”
dragMoveEnabled=”true” styleName=”myText” width=”50%” height=”100%” fontSize=”12″ backgroundColor=”#E2E2E2″/>
</mx:HDividedBox>
</mx:AddChild>

<mx:AddChild relativeTo=”{changeBox}”>
<mx:Label id=”pickHelp” text=”Drag the fields you need from the left column over to the right. You can also re-order by dragging if you need to” styleName=”myText” fontSize=”10″ textAlign=”center”/>
</mx:AddChild>

<mx:SetEventHandler target=”{nextBtn}” name=”click” handlerFunction=”drawDetails”/>
</mx:State>

<mx:State name=”SPEC_FIELDS”>

<mx:AddChild relativeTo=”{changeBox}”>
<mx:HBox id=”headerInput”>
<mx:Label id=”headLabel” text=”Document Header” styleName=”myText” />
<mx:TextInput id=”docHead”/>
</mx:HBox>
</mx:AddChild>

<mx:AddChild relativeTo=”{changeBox}”>
<mx:DataGrid id=”fieldDG” dataProvider=”{fieldAC}” editable=”true”>
<mx:columns>
<mx:DataGridColumn headerText=”Field Name” dataField=”name” editable=”false” backgroundColor=”#E2E2E2″ />
<mx:DataGridColumn headerText=”Max Length” dataField=”maxLength” editable=”true”/>
<mx:DataGridColumn headerText=”Pad Char” dataField=”padChar” editable=”true”/>
<mx:DataGridColumn headerText=”Pre String” dataField=”preString” editable=”true”/>
<mx:DataGridColumn headerText=”Post String” dataField=”postString” editable=”true”/>
</mx:columns>
</mx:DataGrid>
</mx:AddChild>

<mx:AddChild relativeTo=”{changeBox}”>
<mx:HBox id=”footerInput”>
<mx:Label id=”footLabel” text=”Document Footer” styleName=”myText” />
<mx:TextInput id=”docFoot”/>
</mx:HBox>
</mx:AddChild>

<mx:AddChild relativeTo=”{changeBox}”>
<mx:Label id=”specHelp” text=”Only enter data for fields you require. A Max Length of 0 means no limit will be applied” styleName=”myText” fontSize=”10″ textAlign=”center”/>
</mx:AddChild>

<mx:SetEventHandler target=”{backBtn}” name=”click” handlerFunction=”wipeDetails”/>

<mx:SetEventHandler target=”{nextBtn}” name=”click” handlerFunction=”createFile”/>
</mx:State>

<mx:State name=”GENFILE”>

<mx:AddChild relativeTo=”{changeBox}”>
<mx:Label id=”debug” text=”{docHead.text}” textAlign=”center”/>
</mx:AddChild>

<mx:RemoveChild target=”{btnBox}” />
</mx:State>
</mx:states>

<mx:Panel id=”mainPanel” width=”60%” height=”60%” backgroundColor=”#B9B9B9″ backgroundAlpha=”0.51″ alpha=”1.0″ color=”#000000″ layout=”vertical” cornerRadius=”20″ title=”CIF File Creator” borderColor=”#E2E2E2″ themeColor=”#4B4B4B” >

<mx:VBox id=”changeBox” width=”100%” height=”70%” horizontalAlign=”center” verticalAlign=”middle”/>

<mx:HBox id= “btnBox” width=”100%” verticalAlign=”bottom” horizontalAlign=”right” paddingRight=”10″>

<mx:Button id=”backBtn” label=”&lt;Back” click=”back()” styleName=”buttonOfficial”/>

<mx:Button id=”nextBtn” label=”Next&gt;” click=”next()” styleName=”buttonOfficial”/>

</mx:HBox>

</mx:Panel>

</mx:Application>

Posted in Flex. Tags: , . 2 Comments »

Notes on Rocky Mountain Flash Camp (10/12/10)

These are some notes on the recently held Flash Camp in Denver that I attended. I’ve included links to slides where I have them and the recordings that were made of each session (apparently the first 3 sessions had some audio issues).

First off was RJ Owenof Effective UI on the Flex 4 Component Lifecycle (slides,recording) who covered the classic elastic racetrack (for some reason I always want to say electric racetrack), the birth, life and death of components and where the “skin” aspects of Flex 4 come into play. He also covered some performance considerations (such as constructors are not JIT compiled and therefore not optimized so should be as small as possible).

Next up Paul Trani of Adobe covered a Flash CS5 deep dive (recording) going through some of the things you can do with the tool. It was an entertaining session with more of a designer emphasis.

Kevin Hoyt, also of Adobe went next on the Flash Player for Flex Developers (recording). Unfortunately, Kevin’s blog seems to be unavailable while I’m writing this but you should find him at blog.kevinhoyt.org probably after Adobe MAX is finished. This talk was one I’d seen Kevin give before going through a simple app to gather weather data written purely in Flash starting with the stage and using Sprite as the base object for the display components. The end result was a Flash program of ~ 3k compared to a Flex program (using framework libs) of ~100k. This time I remembered to ask him if there were any lightweight Flash frameworks I could look at rather than re-inventing everything myself. His suggestions were AS3CoreLib and MinimalComps.

James Ward (Adobe) talked about Mobile Flash and Flex Development (recording). His session covered the “Tour de Flex” mobile app for Android he’s currently working on using Flex Hero beta. It’s not generally available yet but you can find his code on github.

David Hassoun of RealEyes Media talked about Video on the Flash Platform (recording) which demoed some of the features of the Open Source Media Framework (OSMF)

Jun Heider also of RealEyes Media covered “cool things you can do with Flash Player P2P” (slides and source,recording). I had vaguely heard of Adobe Stratus (now Cirrus) but that was about it so it was interesting to see some examples of how it could be used.

Last but not least was Juan Bonfante of Roundarch talking on Advanced skinning and layout with Flex 4 (code,recording).

RMAUG did a great job putting on this camp and if you’re in the Denver area on November 9th, you should check out their “Mini MAX” event (details on the website).

Learning Flex 4 – States

States are easier to work with in Flex 4 than they were with 3. While Flex 3 had the advantage that everything to do with your states was in one place, it made things more complicated by the additional syntax you had to deal with to add/remove items etc. With Flex 4, you can just add your state name to a property to specify a value specific to that state and specify if components should be included in/excluded from a state. The only downside to this is that your state specific code gets scattered but Flash Builder has an option to show you components by state so that helps there.

Starting from the beginning, you first need to declare what states you are going to have. This is done using the <s:states> tag. Within this, specify one or more <s:State> tags with the name property set to the name for your state. The first State is used as the default. In addition to the name, you may also specify a stateGroups property. This allows you to group states so you can refer to the group rather than all the individual states. This could be useful in the case where for most of the time, you want to do the same thing for several states but for specific components/properties you need a finer distinction.

Here’s an example (I like to use all caps for my state names to help them stand out a little more):

<s:States>
<s:State name="LOADING"/>
<s:State name="EMPLOYEE_VIEW" stateGroups="VIEW" />
<s:State name="MANAGER_VIEW" stateGroups="VIEW"/>
<s:State name="MANAGER_SELECT" />
</s:States>

The grouping is a bit artificial in this case but this app starts in the LOADING state while it’s gathering data from the back end. Then, if you’re a manager, the state becomes MANAGER_SELECT where you can select an employee to view data on, finally you get a MANAGER_VIEW of the data or the EMPLOYEE_VIEW if you logged in as an employee. You can see how there might be several components common to the MANAGER_VIEW and the EMPLOYEE_VIEW which you could use the VIEW stateGroup for but some components (maybe a change pay rate button for instance) would be specific to the MANAGER_VIEW.

You can include components in a state by using the property includeIn or exclude them using excludeFrom.  You can specify more than one state by using commas to separate them in the string (or specify a stateGroup). By adding the state to a group container, you can affect all the components within that group.

You can change properties (including event handlers) by suffixing the property name with the state name you want it to apply to eg – label.LOADING="retrieving data..."

If you don’t specify a state, the component/property is considered to be the same for all states. You can change the state by setting the currentState property (by setting it to the empty string, you return to the default or first state).

Custom components can declare their own states and you can use the currentState property of the instance of the custom component to change the state for that particular object.

When the state changes, the enterState event is fired by the State object being entered and by components entering that state. The exitState event is sent by the State and components being left. The object the currentState is being changed on fires currentStateChanging when it’s about to change and currentStateChange when it’s done.

You can use states within a custom item renderer to react to view states such as hovered, selected and change the presentation for these cases. This article has the details. Saturn Boy has also written a blog post looking at states with skinning.

Where do we go from here?

My previous post completes what was hopefully a good introduction to Flex 3 so what next? Well don’t worry, there’s plenty more stuff out there to learn.

To start with, Flex 4 is in beta now and due to be released some time this year. It’s not a complete redo so there’s plenty that carries over from 3. Many of the changes revolve around the new Spark component set and the way they’ve separated out appearance (with skinning), states (with the new states design) and behavior. This supports the Catalyst tool as I’ve covered briefly in prior posts.

You can download the SDK for Flex 4 Beta2 from here and use it with FlashDevelop (although it only understands the MX namespace right now so it’s MXML autocomplete isn’t very helpful).

There’s a good article on the differences between Flex 3 & 4 here to get you started and that’s certainly something I plan to post more on in the future.

Another avenue for exploration is frameworks – if you’re going to be writing Flex professionally as part of a team or larger apps on your own, you’re probably going to need to know about them. One of the oldest and most well known is Adobe Cairngorm. It’s sometimes criticized as heavy and requiring a lot of boilerplate code but because it’s well known, it’s probably worth at least knowing how it works. A newer contender is the Swiz framework. I’ve seen a couple of presentations on this and plan to get to know it a lot better.

There are plenty of ActionScript libraries you can use, I’ve already written about Google maps and the FLAR toolkit manager but I plan to start looking more into data visualization using Axiis in the future.

All in all, I’d say there’s plenty to keep me busy here!

Learning Flex – Lesson 26, The Basics of Memory Management and Performance

There are two basic ways to handle memory allocation. The first (used by C,C++) is to make the developer deal with it – you are responsible for allocating memory required and freeing it when you’re done. This allows the developer the freedom to decide when time consuming memory operations are done but the responsibility to keep track of everything or run into memory leaks (when unused memory isn’t released) or null pointer issues and the like when it’s released too soon.

The alternative chosen by Flash (and Java) is to use the runtime for garbage collection – i.e. let it decide how to allocate and free memory. The downside to this is that garbage collection can be time consuming and it’s nondeterministic – the runtime decides when it’s going to happen, not the developer.

There are several different algorithms for  garbage collection. The Flash player uses a version comprised of “reference counting” and “mark-and-sweep”. (For a discussion of various garbage collection strategies see this article).

For reference counting, the runtime keeps track of all the active references to an object. Each object keeps a reference internally to its children and each child has a reference to its parent. There are also references created explicitly by the developer as a way to access the object in question. If the reference count is zero, nothing can access that object any more so it can be removed and it’s memory reclaimed.

The second phase, mark-and-sweep is more costly and required to discover circular references – i.e. objects that reference each other but have no outside references. To perform the mark, the player starts at the root of the application and traverses through its references marking each as it goes. When it’s reached the leaf nodes of all those references, any objects not marked can be “swept” away and deallocated. Due to its cost, this operation is performed iteratively over several frames and is only run occasionally.

What does all this mean to a Flash/Flex developer? Well you should be sure to remove all references to an object when you no longer need it. Often this will be done for you with variables going out of scope etc but you should be proactive in removing longer lived references you no longer require.

Event Listener Leaks

Objects that want to be informed of an event can register as a listener using the addEventListener() method. This results in the creation of a reference to the object doing the listening. Therefore if an object is listening for events, it may not be available for garbage collection.

There is a method called removeEventListener() that can be called to remove the reference when it’s no longer required which would allow the listener object to be removed when it has no other references. Unfortunately, it’s not always easy to know when to call this.

An alternative when calling addEventListener() optional parameters may be added, the last of which is a Boolean indicating a weak reference (the default is false). What this means is that if set true, the reference created for the listener is considered weak and not counted as a reference for garbage collection. A listener with only weak references remaining would be eligible for garbage collection. Here’s a post with more on weak references and here’s an opinion on when they shouldn’t be used.

Flash/Flex Performance tuning

FlexBuilder (and now FlashBuilder) professional comes with a profiler tool that allows you to investigate the memory usage of your application and time operations to look for areas in need of tuning.

There are no free alternatives that I’m aware of but you can use flash.utils.getTimer() to time operations and System.totalMemory to keep track of memory use in your application. Grant Skinner also has a performance test harness you might find useful.

A great resource with lots of links to more detailed information on memory management and performance is this page on Jun Heider’s blog.

Learning Flex – Lesson 16, Customizing the Look & Feel of a Flex Application

I’ve written a couple of posts previously looking at some aspects of this lesson but this a more detailed exploration.

There are two key ways to change the appearance of a Flex app – styles and skins.

Style properties allow you to change such elements as font size, background color and text alignment. Skins are graphical elements (either provided as files or created with ActionScript) that change the appearance of a component (eg button shape).

Applying Styles

Flex styles are based on the web standard CSS (Cascading Style Sheets). There are several levels a style may be applied at:

You may specify a single style on a particular component, use a CSS Class selector to set several styles together or use a type selector to specify that all components of a particular type should use the provided style values.

A style may be applied to a component directly in its MXML definition by adding the style name as a property and specifying it’s value such as

<mx:Label id="mLabel" text="My Label" fontWeight="bold"/>

to display a bold label. The setStyle() method can also be used to achieve the same effect – mLabel.setStyle("fontWeight","bold")

Note that when using setStyle() and specifying colors, the prefix 0x is used to indicate a hexadecimal value (and quotes are not required around them). When specified in a tag or CSS attribute, the prefix # may be used instead.

setStyle() is an expensive run time operation so it’s use should be limited.

The Flex language reference will tell you what styles are available for a particular component and will also specify CSS inheritance. If yes, this indicates that if the parent of this component has a value specified for the style, the child component will use the same value unless it has its own value specified. (For example, if you have a Label in a HBox, it will inherit the HBox color (text color) unless it has its own color value set.

Setting Styles with CSS

The <mx:Style> tag can be used to define local styles using CSS based syntax. Flex supports CSS class selectors which define a set of properties as a single class that can then be used by specifying the class name for a component’s styleName property.

<mx:Style>
.myStyle{
color:#FF00FF
selectionColor:#00FF00
}
</mx:Style>

<mx:ComboBox styleName=”myStyle”/>

You may also use CSS type selectors which define a set of styles to be applied to all instances of a component type.

<mx:Style>
ComboBox{
color:#FF00FF
selectionColor:#00FF00
}
</mx:Style>

<mx:ComboBox id="myBox1"/>
<mx:ComboBox id="myBox2"/>

Both myBox1 and myBox2 will have the same color and selectionColor.

Note that Flex does not support ID selectors.

Flex will support traditional CSS style formatting for the properties it supports (ie all lowercase with hyphen to separate words such as background-color) within a Style tag but for attributes that are specific to Flex and all attributes outside of Style tags, the camel case form of the name is required (eg backgroundColor). This is because the hyphen is not a valid character for XML attributes and MXML tags must be valid XML.

CSS properties that require multiple values are specified using a comma separated list of values. It’s important to note that those properties must have at least two values (even if they are the same) to avoid an error as a single value will not map correctly to an array.

You may also use mx:Style to specify an external CSS file to compile into the app using the source attribute. This should always be placed within the file containing the Application tag  – setting style imports in child documents can give rise to unexpected results.

Run Time CSS

The disadvantage of specifying an external file to load in this way is that it is compiled into the application and thus any changes to the CSS require the app to be re-compiled. By loading the CSS at run time, this situation can be avoided and different CSS files could be loaded depending on data provided so if for example, you had a collage sports app, you could brand your app with the team colors of where your users login from.

Flex can’t deal directly with a CSS file but the compiler can convert that to a SWF which it can use. To do this in FlashDevelop, right click the CSS file, select “always compile”, go to project properties and specify the output filename you want to use and compile (don’t forget to switch back to your regular app when you’re done).

Once you have your CSS SWF, just use

StyleManager.loadStyleDeclarations("myCSSFile.swf")

to load it. A second optional parameter is update a boolean (which defaults to true). If set, this forces an update of all the styles in the application. If you’re loading several CSS SWF files, you should set this to false for all but the last one to reduce the overhead of this operation.

you may also use

StyleManager.unloadStyleDeclarations("myCSSFile.swf")

to unload a CSS. This also has an optional update parameter with the same effect.

It’s possible to have several levels of style in play, the rule being that if a style is defined in multiple places, the last one loaded is the one used.

Thoughts on Catalyst

I haven’t played too much with this tool yet and it is still in beta so it’s hard to be too definitive with any opinions right now but there are some things I can say about it.

As a tool for creating prototypes and demos, I think it has a lot of promise. It doesn’t seem to take too long to create something that will give you an idea of the user experience you’re developing.

To use it for full on development projects, it has a few drawbacks. Not all components have a Spark version yet and it won’t do round-trips right now so if you try and take a project you went to FlashBuilder with back into Catalyst, it complains. It’s still beta and from Adobe’s marketing material, it seems like they intend to have all that working at some point so those  may be moot points later. A bigger potential problem in my view is how do you deal with an existing code base of lovingly crafted custom Flex4 components? If your designer uses Catalyst, it will be pumping out nicely skinned standard components and as a developer, you’re going to have to tease all of those out and replace them with your custom work where necessary.  It’s going to get tough if you’ve got skinning involved in those components too. You’re also going to get one big monolithic app that probably doesn’t match up too well with any design patterns.

This is not to say that with planning and careful consideration of what you’re doing, you couldn’t make it work but for bigger apps it’s not going to be a trivial task to take something from Catalyst and make it work effectively.

I think  if you were to use it to create the starting point for your reusable components and then still continue to do your main construction within Flasbuilder, you’re probably going to get the best results.

I’ll be interested to see if I can find anything on using it for larger projects and see what people come up with.