FlashPlatformist
Articles, Information, News, & Tutorials for Adobe Flash Platform Developers and Architects

Building Custom Components with Flex 4

Upon conducting the necessary research for my current chapter in Flex 4 in Action that I am working on, I felt it would be worthwhile to post a blog to help clarify some confusion that may be surrounding the Flex 3 versus Flex 4 components. Contrary to my previous post, I’m not speaking from an architectural standpoint, but a simple “what is and what isn’t” checklist to hopefully help save you some time as you learn the Flex 4 SDK.

Where do Spark Components come from?

A Flex 4 Spark component is simply an extension of the Flex 3 (Halo)UIComponent base class. Additional classes are stacked on top of UIComponent primarily to separate the presentation layer from the business layer. This is primarily accomplished with the Group and SkinnableComponent classes in the Spark library. These classes are hooks into the extended functionality of the Flex 4 Spark library, while still keeping that of the Flex 3 Halo libarary. You may be asking yourself at this point - how does one get the best of both worlds then?

The Group and SkinnableComponent classes both extend the UIComponent base classs. If you are familiar with Flex 3, then I certainly hope you are familiar with the UIComponent class. If not, I suggest reading up on it before going any further with any Flex development.

As you might expect, most of the viewable components in the Spark library extend either the Group or SkinnableComponent class. The only difference between the two is that Group is used to improve performance and minimize application size because it does not include the added weight of skinning. Therefore, if you are building a component that does not require skinning, then use Group as your base class. If you want your component to be skinnable via a separate Skin class, extend one of the base classes that are derived from SkinnableComponent.

Example Scenarios

For example, if you are building a composite container component to hold a series of unrelated display objects, extend the SkinnableContainer class. This gives you the ability to attach a separate Skin class to the container, which could be straight FXG exported from Flash Catalyst that a designer may have given you for the component.

Another example might be if you are building a custom component that will hold data in the form of item renderers. In this case, you should extend the SkinnableDataContainer class, or even the Spark ListBase class. However, a component like the Flex 4 VideoPlayer is built directly from the SkinnableComponent class instead of SkinnableContainer. Which class you should use is ultimately a judgement call based on how lightweight you need the component to be.

Of course, the more you get to know the code inside the Spark library classes, the easier it will be to figure out which class you should extend when building custom Flex 4 components.

Possibly Related Posts:


Share/Save/Bookmark


Posted by Dan Orlando on June 28th, 2009 :: Filed under Tutorials

Understanding the Flex 4 Spark Component Architecture and how to Build Custom Components with the Flex 4 SDK

The architecture of the new Spark components in Flex 4 supercedes the Halo components of Flex 3. Upon learning how to leverage the  architecture of Spark components, you will find the improvements to be quite substantial.

Ultimately, the new component architecture with the Spark library makes building, modifying, and designing custom components a lot easier and far more intuitive. The most significant architectural changes are internal state management and decoupled visual appearance.

Internal State Management

The declaration of global application states is still possible, but the trick to getting a Flex application to closely resemble a native desktop application is by changing the state of individual container components while holding the state of others. This is what gives the application a “seamless” flow. This is accomplished by creating multiple skins for a single component, and just swap them out in an event handler. The code for the skin itself should have the following structure:

<Skin xmlns="http://ns.adobe.com/mxml/2009">

    <states>
        <State name="up" />
        <State name="over" />
        <State name="down" />
        <State name="disabled" />
    </states>

    ...
</Skin>

In the example above, state changes are controlled by the component, as the component class is responsible for internal behaviors. However, a single state change could include the attachment of a new skin class.   In addition to controlling it’s currentState property, the component broadcasts this value to its parent through the use of meta data. That means the parent can still override the built-in states of a component, and most importantly, the parent application is able to easily find out the current state of any of its children.

Decoupled Visual Appearance

HOWEVER, skin states are not the same as component states. A component state can change without the skin state changing. In other words, component states are decoupled from skin states. Component states define changes to the behavioral state of a component, while Skin states define changes to the display state of the component that they are attached to. For example, the Button class has a set of states that include: up, down, selected, and disabled. The Button drives state changes to ButtonSkin, which is the skin that is attached to the Button component. The Button and ButtonSkin classes both have their own currentState property, which is accessible by the parent container. This is a good example of the Template design pattern.

The following code sample is taken from ButtonSkin.mxml and provides a nice depiction of what we are talking about here:

<?xml version="1.0" encoding="utf-8"?>
<Skin xmlns="http://ns.adobe.com/mxml/2009">

    <Metadata>
        [HostComponent("spark.components.Button")]
    </Metadata> 

    <states>
        <State name="up" />
        <State name="over" />
        <State name="down" />
        <State name="disabled" />
    </states>

    <!-- border -->
    <Rect left="0" right="0" top="0" bottom="0" minWidth="70" minHeight="24">
        <stroke>
        <SolidColorStroke color="0x808080" color.disabled="0xC0C0C0" />
        </stroke>
    </Rect>

    <!-- fill -->
    <Rect left="1" right="1" top="1" bottom="1" minWidth="68" minHeight="22">
        <stroke>
        <SolidColorStroke color="0xFFFFFF" color.over="0xFAFAFA" color.down="0xEFEFEF" />
        </stroke>
        <fill>
        <SolidColor color="0xFFFFFF" color.over="0xF2F2F2" color.down="0xD8D8D8" />
        </fill>
    </Rect>

    <!-- label -->
    <TextBox text="{hostComponent.label}"
         fontFamily="Arial" fontSize="11"
         color="0x444444" color.disabled="0xC0C0C0"
         horizontalCenter="0" verticalCenter="0"
         left="10" right="10" top="4" bottom="2"
         textAlign="center" verticalAlign="middle">
    </TextBox>

</Skin>

Now that you have reviewed the code for the default Spark skin class that is used by the <code>Button</code> component, let’s take a look at the code for the <code>Button</code> component in the Spark library:

package spark.components {
/**
 *  Up State of the Button
 */
[SkinState("up")]
/**
 *  Over State of the Button
 */
[SkinState("over")]
/**
 *  Down State of the Button
 */
[SkinState("down")]
/**
 *  Disabled State of the Button
 */
[SkinState("disabled")]
public class Button extends SkinnableComponent implements IFocusManagerComponent {  

    /**
     *  @return Returns true when the mouse cursor is over the button.
     */
    public function get isHoveredOver():Boolean {
        return flags.isSet(isHoveredOverFlag);
    }

    /**
     *  Sets the flag indicating whether the mouse cursor
     *  is over the button.
     */
    protected function setHoveredOver(value:Boolean):void {
        if (!flags.update(isHoveredOverFlag, value))
            return;

        invalidateSkinState();
    }

    // GetState returns a string representation of the component's state as
    // a combination of some of its public properties
    protected override function getUpdatedSkinState():String
    {
        if (!isEnabled)
            return "disabled";

        if (isDown())
            return "down";

        if (isHoveredOver || isMouseCaptured )
            return "over";

        return "up";
    }

    //--------------------------------------------------------------------------
    //
    //  Event handling
    //
    //--------------------------------------------------------------------------

    protected function mouseEventHandler(event:Event):void
    {
        var mouseEvent:MouseEvent = event as MouseEvent;
        switch (event.type)
        {
            case MouseEvent.ROLL_OVER:
            {
                // if the user rolls over while holding the mouse button
                if (mouseEvent.buttonDown && !isMouseCaptured)
                    return;
                    setHoveredOver(true);
                break;
            }

            case MouseEvent.ROLL_OUT:
            {
                setHoveredOver(false);
                break;
            }

        }
    }
}

}

As you can see in the third code listing, a SkinState meta data declaration is used to define the states of the attached skin. To change skin states, you should use invalidateSkinState() and getCurrentSkinState(). The invalidateSkinState() method is what invalidates the skin state, and sets the skin’s state to that which is returned by the getCurrentSkinState() method. The getCurrentSkinState() method keeps track of any internal properties on the component and figures out what state the skin should be in.

This may seem a bit complicated at first, but as you begin to develop your own custom Flex 4 components, it will quickly become apparent that this is a very valuable architectural change to components for this new iteration.

Possibly Related Posts:


Share/Save/Bookmark


Posted by Dan Orlando on June 13th, 2009 :: Filed under Tutorials
Tags :: , ,

Adobe Flash Builder 4: Data-centric Features for PHP (PHPBuilder.com)

I just ran across an article I wrote during the Flash Builder 4 beta pre-release, which was apparently published today (of course, no one tells me these things, which is ironic). It discusses the new Data-centric features for PHP built into Flash Builder 4.

Coming from a PHP background, my goal was to help accelerate the learning curve involved with getting to know the powerful new RIA tools into your development workflow. It is really worth learning how to utilize these new features, I guarantee it will speed up your workflow ten-fold once you get the hang of using them.  So check it out!

PHPBuilder.com - Adobe Flash Builder 4: Data-centric Features for PHP

PHPBuilder.com - Adobe Flash Builder 4: Data-centric Features for PHP

Possibly Related Posts:


Share/Save/Bookmark


Posted by Dan Orlando on June 9th, 2009 :: Filed under Announcements, Flash Platform News
Tags :: , , ,

Data-centric Adobe Flash Builder development with the Zend Framework

The first of a series of articles I recently wrote on the Data-centric features of Flash Builder 4 was recently published on the Zend Developer Zone. Obviously this article focuses on the built-in automated data-centric development features for PHP and the Zend framework in Flash Builder 4 beta. Check it out.

Data-centric Adobe Flash Builder development with the Zend Framework

Data-centric Adobe Flash Builder development with the Zend Framework

Possibly Related Posts:


Share/Save/Bookmark


Posted by Dan Orlando on June 4th, 2009 :: Filed under Announcements, Flash Platform News, Tools & Innovation
Tags :: , , ,

Designing (RED)Wire, Part 3: Advanced Styling Methods for Enhanced User Experience with Adobe Flex and AIR

Introduction

In the last segment, you learned how to leverage CSS to style components for large-scale Flex and AIR applications. In part three of this series, you will discover how to style application components programmatically.

The 3D interactive menu state of the application required some programmatic styling in order to lay out the 3D planes properly in their respective positions

The 3D interactive menu required some programmatic styling in order to position the 3D planes properly

Using the getStyle() and setStyle() Methods

All components derived from the UIComponent base class inherit two methods, called getStyle() and setStyle(). These two methods provide an incredible amount of flexibility to the developer, especially for programmatic skinning. Although covering all the possible uses of this functionality is beyond the scope of this article, I will show you a couple of different uses of it to demonstrate the power behind this functionality, as follows:

private function toMinimized():void {
	   TaskBarManager.addToTaskBar(this);
	   pushStateProperties(stateMin, x, y, 200, titleBar.height, NaN, NaN);

	   minimizeButton.setStyle("upSkin", getStyle("restoreButtonUpSkin"));
	   minimizeButton.setStyle("disabledSkin", getStyle("restoreButtonDisabledSkin"));
	   minimizeButton.setStyle("downSkin", getStyle("restoreButtonDownSkin"));
	   minimizeButton.setStyle("OverSkin", getStyle("restoreButtonOverSkin"));

	   maximizeButton.setStyle("upSkin", getStyle("maximizeButtonUpSkin"));
	   maximizeButton.setStyle("disabledSkin", getStyle("maximizeButtonDisabledSkin"));
	   maximizeButton.setStyle("downSkin", getStyle("maximizeButtonDownSkin"));
	   maximizeButton.setStyle("OverSkin", getStyle("maximizeButtonOverSkin"));

	   dispatchEvent(new Event("minimize"));
}

The toMinimized method seen in the code listing above is taken from a custom component that extends the Flex Panel class, and gives the appearance of a new window within the application that can be minimized so that only the title bar is showing in case the user has to access something that is behind it. The cool thing about it, is that when the window is in the minimized state, the minimize button is re-skinned on the fly using the setStyle method, which turns the button into a “restore” button, and the new state for the maximize button skin is also set. Essentially, we are reusing the same instance of a class by using it as a toggle button programmatically. Here is another example, this time using MXML:

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

	<mx:states>
		<mx:State name="MyLibraryState">
			<mx:AddChild position="firstChild">
				<comp:CollectionsLibrary height="100%" width="100%"
					horizontalCenter="0" verticalCenter="0">
				</comp:CollectionsLibrary>
			</mx:AddChild>
			<mx:SetStyle name="backgroundImage"
				value="@Embed(source='com/assets/my_collections_background.png')" />
			<mx:SetProperty target="{vbox1}" name="y" value="442.95"/>
		</mx:State>
	</mx:states>
	(…)

The setStyle method is also conveniently available to the developer through MXML using the syntax: . The code listing above sets a new background image when the state of the application is changed.

Compiling Style Sheets to Load at Runtime

An interesting feature in Flex 3 is that a CSS file can be compiled as a SWF and loaded at runtime. Using this feature, you could allow the user to change the look and feel of your application based on their own personal preference. You may have seen this type of functionality used on social media web sites, where JavaScript is used to swap CSS files when the user selects a new design view.

Not surprisingly, accomplishing this is very easy in Flex. Simply create a new CSS file, place your CSS style selectors in it, and save the file. Then, in the Flex navigator panel (upper left panel when in “Flex Development” mode), right click the CSS file you just created and select the option “Compile CSS to SWF”.

The CSS for the 3D interactive menu was loaded at runtime to layout the 3D planes. In this instance, the CSS information was loaded from a local database and parsed using a custom CSS parser class.

The CSS for the 3D interactive menu was loaded at runtime to layout the 3D planes. In this instance, the CSS information was loaded from a local database and parsed using a CSS parser/helper class

The StyleManager class

After you have created and compiled all of the CSS style sheets that you want to use in your application to separate SWF files, the Flex StyleManager class can be used to easily switch between style sheets, as demonstrated in the following code listing:

private function loadFirstStyleSheet():void {
	StyleManager.loadStyleDeclarations("CSS1.swf");
}

private function loadSecondStyleSheet():void {
	StyleManager.loadStyleDeclarations("CSS2.swf");
}

Computational Expense

One very important thing to take into consideration when loading precompiled style sheets at runtime is the load that you are putting on the user’s system as a result. This method of design implementation should be used conservatively and with extreme caution, as doing a lot of it will quickly degrade the performance of your application due to a lack of available system resources.

Conclusion

In this article series, you have seen a number of methods and techniques for implementing CSS in large-scale Flex applications. Interestingly, the Flash Platform has evolved so much in the last six months, that this article series barely scratches the surface. User Experience Design is taken to the next level with the proliferation of Flash Catalyst and Flash Builder, both of which will be in public beta in a matter of days. Additionally, the Flex 4 SDK expands on the already powerful capabilities of CSS within Flex, making the Flash Platform even more lucrative for RIA development and the number one choice for providing the best possible User Experiences.

Possibly Related Posts:


Share/Save/Bookmark


Posted by Dan Orlando on June 1st, 2009 :: Filed under General, User Experience
Tags :: , ,

Getting Started with Flash Builder 4 beta and Flash Catalyst beta

The moment that many Flash Platform developers around the world have been waiting for is finally here - Flash Builder (beta) and Flash Catalyst (beta) are now available for download from the Adobe Labs web site.

A Milestone for Rich Application Development

After many months of rigorous testing, migrating, conducting Q-A, and discussing issues in the pre-release forums to solve complex problems, the official public betas were finally dropped early this week.

As noted by Adobe, the intent of these beta releases is to improve upon three critical facets of the development life cycle: developer productivity, designer-developer workflow, and data-centric application development. The extent of the features that have been included in what used to be labeled “Flex Builder” are so ginormous that you will likely agree that it was worth slapping an entirely different name on it. It is clearly light years beyond Flex Builder 3. The release of these two programs to the public - though still in beta - mark a significant milestone in the evolution of RIA technology as a whole nonetheless.

Getting Started, Step-by-Step

In the spirit of all Adobe beta releases, a number of valuable documents and multimedia  resources have been made available to help you get acquainted with these new products:

  1. Begin by reading Tim Buntel’s article on the Adobe Developer Connection, titled What’s new in Flash Builder 4 beta.
  2. Next, Joan Lafferty points out exactly what is different between the Flex 3 SDK and the Flex 4 SDK beta.
  3. Learn about the new Flex SDK features in Matt Chotin’s “What’s new in Flex 4 SDK beta” article.
  4. Once you’re ready to really dive in, check out the collection of tutorial videos on the Adobe Labs site. While you’re at, make sure you don’t miss Lee Brimelow’s 2-part video tutorial series. Lee made the first tweet announcing the release and followed it with a nice little tutorial to complement the announcement. A few hours later, he released Part 2 of the tutorial, also very nicely done. Great job on these Lee.
  5. Then take some time to peruse through the livedocs for the Flex 4 SDK and Flash Builder that were just recently made public.
  6. Install the programs and begin to familiarize yourself. Links to the respective pages where the betas can be downloaded are provided below.
  7. Check out this tutorial by Andrew Shorten on Building a data-centric application using Flash Catalyst beta and Flash Builder 4 beta.
  8. After you’ve installed the programs, reviewed the available resources and taken a little time to familiarize yourself with the applications, its time to take a trip over to the Flash Builder 4 user forum and the Flash Catalyst user forum to discuss and collaborate with other members of the community.
  9. Install the Tour de Flex AIR application and use the new Flex 4 SDK examples to hit the ground running in Flash Builder 4 beta.

Download the Betas

Possibly Related Posts:


Share/Save/Bookmark


Posted by Dan Orlando on May 31st, 2009 :: Filed under Flash Platform News

Designing (RED)Wire, Part 2: Taking the User Experience from Concept to Production with Flex and CSS

Introduction

In the first segment of this series on designing the user interface of (RED)Wire, you learned about the different techniques and applications of CSS with Flex and AIR applications. In part two of the series, you will learn how these techniques can be applied to application components in enterprise level Flex and AIR applications. You will also discover the value of using external stylesheets when developing your Flex user interfaces.

All of the style information for (RED)Wire was contained in a single, well-commented style sheet. Additionally, all of the assets that were part of the user interface were contained in a single SWF file and loaded on demand.

All of the style information for (RED)Wire was contained in a single, well-commented style sheet. Additionally, all of the assets that were part of the user interface were contained in a single SWF file and loaded on demand.

Applying styles in Flex

Choosing your method of CSS implementation with Flex must be based on the situation and the environment. It is important to look at the application you are designing from the conceptual 50,000-foot view when considering your options for design implementation. The following are the most common methods for using CSS with Flex:

Setting Styles on an Instance (inline)

Flex components that extend the Flex UIComponent base class will allow you to set common styles as properties “inline”, or in other words, within the MXML component declaration tag. The layout properties of a display object are often unique to that object, so it is common to see any one of the following properties set explicitly on a component: x, y, height, width, top, right, left, bottom, horizontalCenter, verticalCenter, horizontalAlign, and verticalAlign.

<mx:Button id="volumeIcon" cornerRadius="0" alpha="0.9"
	verticalCenter="0" enabled="true" toolTip="Volume Control"
	click="toggleVolumeControl();" />

The listing above exhibits a functional example of setting style properties that are unique to the specific instance of the Button component with an id value of volumeIcon. Since I know that this is the only button that will require these particular style values, I have explicitly set the cornerRadius, alpha, and verticalCenter of this particular button.

A good rule of thumb when setting style properties on an MXML component tag is that the only reason you should be setting the property this way is because you know that the particular property value you are setting is specific to that component. For instance, let’s say your application requires a container that vertically stacks display objects, but without any gap in between. At the same time, you know that other VBox containers in the application do need to have some spacing between the display objects. In this type of situation, you should explicitly set the verticalGap property on that instance of the VBox component, as the following listing demonstrates:

<mx:VBox id="myVBox" verticalGap="0"
	x="15" y="15" width="100%" height="100%">

(...)

</mx:VBox>

Embedding CSS in MXML

This method involves embedding styles or assets directly into an mxml file with the tag. For all practical purposes, there are few instances in which directly embedding style information into an mxml file makes sense. It is important to recognize that as the application grows, the design will become harder and harder to maintain if there is a lot of embedded CSS throughout the application. With that in mind, it is important to be conservative with this method and only use it when necessary. The following code illustrates an example of an embedded style declaration that really should be held within an external CSS file for greater code maintainability.

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication
	xmlns:mx="http://www.adobe.com/2006/mxml"
	layout="absolute"
	showFlexChrome="false"
	borderStyle="none"
	keyUp="{this.onKeyStrokeEvent(event);}">

	<mx:Style>
		.bGroup {
			borderSides:"left,bottom,right";
			borderStyle:"solid";
			borderColor:#6d6f71;
			borderLeftThickness:3;
			borderRightThickness:3;
			borderBottomThickness:1;
			dividerColor:#6d6f71;
			dividerThickness:3;
		}
	</mx:Style>

	<mx:Script>
		<![CDATA[ 

			(...)

However, that is not to say that it will never happen. The next code listing is a component based on the Flex AplicationControlBar. In the design that was provided, each button in the control bar is just a single word of text, and looks more like a link than a button.

Notice the seamless integration of the ApplicationControlBar component in the upper right corner (click to view enlarged version).

Notice the Unique Styling of the ApplicationControlBar component in the upper right corner (click to enlarge)

Additionally, each of these one-word links have a small bullet separator between them. Since I had the design for the full application already, I knew this bullet separator was unique to the application’s main control bar and did not appear anywhere else. Most importantly, since the bullet appeared several times within the same component, it made perfect sense to embed the image, as it’s own private class within the MXML file, so that I could bind to it from each of the Image controls that I placed between the links. Otherwise I would have ended up with multiple instances of the same exact image being created, which is nothing more than a waste of system resources.

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

 <mx:Script>
        <![CDATA[

            [Embed(source="assets/bullet_black.png")]
            [Bindable]
            private var bullet:Class;            

        ]]>
    </mx:Script>

	<mx:HBox x="10" y="10" id="hbox" horizontalGap="10" width="350">
		<mx:LinkButton label="Help" styleName="appBarButton"/>
		<mx:Image source="{bullet}" />
		<mx:LinkButton label="About" styleName="appBarButton"/>
		<mx:Image source="{bullet}" />
		<mx:LinkButton label="Minimize" styleName="appBarButton" />
		<mx:Image source="{bullet}" />
		<mx:LinkButton label="Quit" styleName="appBarButton"/>
	</mx:HBox>
</mx:ApplicationControlBar>

External Style Sheets

A Flex or AIR Application will have a single MXML file at the root of the source code directory that is based on either the Application class (Flex), or the WindowedApplication class (AIR). This is the default MXML application file that starts with either or . The application’s style sheet source should immediately follow the declaration of the application’s base class, as seen below:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication
	xmlns:mx="http://www.adobe.com/2006/mxml"
	layout="absolute"
	showFlexChrome="false"
	dropShadowEnabled="false"
	borderStyle="none"
	applicationComplete="{this.appInit(event);}"
	>

	<mx:Style source="com/passalong/assets/RED_SKIN_MAIN.css"/>

	<mx:Script>
		<![CDATA[
			...
                ]]>
        </mx:Script>

The easiest and safest way to maintain the style settings of an application is by using external style sheets. In fact, you could reasonably maintain all of the styles of a large application from a single CSS file. I choose to use only one CSS file for two reasons; first, I always know where to find my style settings, and second, it makes finding styles easy for other developers when working in a team environment. Additionally, it is good practice to keep this file well organized, because as the application grows, your CSS file will inevitably grow as well.

The custom help component went through 5 design iterations. This wasnt a problem though because it was completely driven by CSS.

The custom FAQ component I built went through 5 design iterations. This wasn't a problem though because it was completely driven by CSS (Click to see the functional component).

When building your main application CSS file, it is generally good practice to place your default component style declarations first. For instance, if you want all of your tooltips to look the same throughout your application, use ToolTip as the name of the style and place it toward the beginning of the file. I tend to place a tooltip on just about anything I can in my applications to make the application as user-friendly as possible. Therefore, the tooltip component shows up in my applications more than probably any other component. Since your default component styles have the most impact on the overall look and feel of your application, you need to have quick and easy access to them. This is why it is usually a good idea to place those styles first.

Keep in mind that in most applications, you won’t be able to get away with just creating a default style for each component and calling it a day. The Button component is a good example of this. In order to keep your CSS code tidy, also consider grouping component style subsets together. For instance, a design with three alternate button styles called: Button.musicPlayerPlay, Button.pageDown, and Button.backToMenu, would be placed one after the other in the style sheet and separated by comments from other style groupings.

Conclusion

The bottom line is that in most cases, the most lucrative method for managing and maintaining the design of a Flex user interface is by use of external style sheets. In this regard, Flex is not much different from a standard web application. The methodology is the same: the more you keep styling, layout, and behavior separated from each other, the more manageable your application will be.

Possibly Related Posts:


Share/Save/Bookmark


Posted by Dan Orlando on May 31st, 2009 :: Filed under User Experience
Tags :: , ,

Designing (RED)Wire, Part 1: How to Use CSS to Create Jaw-Dropping User Interfaces with Flex and AIR

Introduction

One of the most powerful features of Adobe Flex is the vast amount of design flexibility that it contains. This is largely due to Adobe’s implementation of Cascading Style Sheets with Flex. For instance, when developing the User Interface of (RED)Wire, an application built on Adobe AIR, I received a number of change requests 2 days before the official launch of the first public release to 160,000 users that were already pre-registered worldwide, eagerly waiting to download their application. While many developers I know would have probably spent the next thirty minutes complaining to fellow developers about how these last-minute requests were an atrocity and an abomination to mankind, I had the changes completed and checked into subversion in less than twenty minutes, thanks to the power of Flex and CSS. It took longer to convince the Technical Director that the changes were complete than it did to complete them.

The main menu State of (RED)Wire, a digital music magazine built with AIR

The main menu state of (RED)Wire, a digital music magazine built with AIR

There are certain inevitabilities that I have learned to expect and prepare for through my experience as a Developer, Architect, and most of all, as a Technical Project Manager.  One such inevitability is that regardless of how much planning is done beforehand, both the design and the functional requirements of a given software project will change, and will change often through the development life cycle (this is the reasoning for the Agile Development methodology, but we’ll save that one for another day).

Change is one of the few certainties when developing large-scale applications in a team-based environment, and the best way to play a winning game is to anticipate the moves of all the players involved and position yourself accordingly before they can make their move. When you learn how to master this development technique, then you are guaranteed to always be in the lead and hitting a moving target (the project requirements) become a lot easier all of a sudden. It is for this reason that I enjoy developing with Flex as much as I do, because Flex features like CSS integration give you the power to do exactly that.

My goal is that by the time you finish reading this series of articles on the design methodologies that I used when creating the (RED)Wire user interface components, you will have learned a number of techniques for utilizing CSS with Flex, particularly with enterprise level applications.

Why Use CSS?

Most object-oriented design patterns keep the design logic separate from behavioral functionality. Since ActionScript is an object-oriented language, it only makes sense to remain consistent with these OOP conventions. The benefits of doing so include: flexibility, keeping maintenance of the application easy as it grows, code reuse, and better performance.

In the world of web design, CSS is a standard for encapsulating the code that makes up the design of a web site. Given the power and maturity of CSS, most experienced web designers strive to implement as much of the design and layout properties of a web site in CSS. The result is much greater control and flexibility over the look and feel of the site. CSS gained most of its popularity approximately three to four years ago when web developers began to realize that when the design of a web site is independent of the site’s behavioral functionalities, the design can be easily modified without the risk of breaking or otherwise negatively impacting the site’s behavioral code. This is what propelled the rapid growth of templates, skinning, and re-skinning the same code base. For example, I am an avid user of WordPress for my blog web site. There are tens of thousands of people that use this same open source code base to power their blog site, and yet, many times you will stumble upon a site built on WordPress and you wouldn’t even know it thanks to it’s impressive separation of code from design through the use of CSS.

Many major magazines use wordpress because of the variety of layouts available thanks to the separation of layout from styling

Magazines use Wordpress largely because of the ability to plug-in new templates on the fly thanks to CSS.

CSS in Flex Improves on what you already know

First and foremost, for those of you coming from a web design background, it is important to understand that Flex CSS does not follow the same conventions as the W3C CSS spec. The hyphen that is used to separate words in the W3C CSS 2.0 specification is not used as part of the code convention in the Flex implementation. Instead, the Flex implementation of CSS uses camel case. For example, vertical-center in the W3C CSS2 spec is equivalent to verticalCenter in Flex CSS. If you are already programming in a language that uses camel case however, this is pretty easy to get used to. The good news is that most of what is available in the CSS 2.0 specification is also available with the Flex CSS implementation. Furthermore, the Flex implementation of CSS expands significantly on the CSS 2.0 W3C standard, offering additional style properties that are unique to the Flex components.

Maintaining Styles - Component vs. Style Properties

Before you begin creating Flex CSS style sheets, I recommend that you first consider how you want your styles implemented. For the sake of simplicity, I am going to show you four basic methods of declaring a style.

Components

A style can be set on a component by using the component’s class name as the style name, like so:

TitleWindow {
   borderColor: #f7f7f7;
   borderAlpha: 1;
   borderThicknessLeft: 0;
   borderThicknessTop: 0;
   borderThicknessBottom: 0;
   borderThicknessRight: 0;
   cornerRadius: 0;
   headerHeight: 0;
   highlightAlphas: 1, 1;
   headerColors: #f7f7f7, #f7f7f7;
   footerColors: #f7f7f7, #f7f7f7;
   backgroundColor: #f7f7f7;
   dropShadowEnabled: true;
}
The TitleWindow component design from (RED)Wire, driven entirely by CSS

The TitleWindow component design from (RED)Wire, driven entirely by CSS

Style Names

Styles can also be declared using a unique style name. Make sure you put a dot in front of it though and use the camel case convention:

.altText {
	fontFamily: TVNordEFCEOP-RegularCon;
	fontSize: 18;
	color: #FFFFFF;
}

Component + Style Name

A style name can also be set on a component when you need to have multiple designs for the same component, which is common for applications that have multiple view states. This also ensures that only the specified component can have that particular style assigned to it:

Text.bigYellowText {
	color:#EFB526;
	fontSize:36;
	fontWeight:Bold;
}

The Global Selector

The global selector is a special kind of selector that will impact every component within the application that contains the properties that are set inside of it. For example, I could set the cornerRadius style property of all of my display object components that contain a cornerRadius style property to a setting of 4, like so:

global {
	cornerRadius: 4;
}

Understanding Style Precedence

While the global selector basically sets a default value of a property, it is easily overridden. For instance, if I set the cornerRadius property of the Button component to 0 either inline or in my CSS file, it will take precedence over the global default setting of 4 that I have also specified, and thus all of my Buttons will contain a cornerRadius value of 0. Furthermore, I can override both the global setting of 4 and the Button setting of 0 by creating an additional style such as:

Button.altCornersButton {
	cornerRadius: 8;
}

Conclusion

Congratulations, you have learned the basics of CSS implementation in Flex and AIR applications. However, there is a lot more to cover. In part two of this series, you will learn how to apply these concepts to application components in an enterprise application development environment, as I did in the implementation of the user interface of (RED)Wire.

Possibly Related Posts:


Share/Save/Bookmark


Posted by Dan Orlando on May 30th, 2009 :: Filed under User Experience
Tags :: , ,

A Real-World Perspective into the Life of a Consultant

Generally speaking, I hope that the readers of my postings will leave having felt like they’ve gained something important - a fulfilling learning experience, if you will. This time, I decided to do something a little different. If you are, or have ever been a consultant, and feel like spending a few minutes on the lighter side of life, you’ll certainly enjoy this real world depiction of our lives, in well, a couple of “different” contexts.

Possibly Related Posts:


Share/Save/Bookmark


Posted by Dan Orlando on May 28th, 2009 :: Filed under General