Leave That Thing Alone Blog

Flex 4 Custom Preloader

In this example were going to look at a way to create a custom preloader SWC in Flash Professional and use it inside of a Flex 4 application by extending the SparkDownloadProgressBar class.
This preloader will display the progress percentage of loading and also a count of RSLs as they are being loaded, after loading is complete the progress of initialization will be displayed. Both of the progresses will be displayed by a graphical progress bas and in text.

View Demo Preloader App (right click for source view)

The preloader may fly by, so lets first take a look at how this progress bar looks as it is loading the Flex app:
flex 4 preloader

The next screenshot shows the progress as RSLs are being loaded:
flex 4 preloader

Finally the progress of initialization, with a second progress bar:
flex 4 preloader

Creating the Preloader SWC in Flash Pro

In Flash professional we create a custom preloader. In this example there are several layers which the design is created from. The layer 'prog_bar' and 'initilize_bar" hold shapes that we will use to resize to show progress. The 'loading text' layer contains some dynamic text that has Character Embedding for upper/lower/numbers. The layers look like this:

flex 4 preloader

The custom preloader FLA can be found in the example by viewing source.

The FLA preloader is a movie clip and its properties are set for "Export for ActioScript" the "Class" property is set to "PreloaderDisplay" this allows us to have a PreloaderDisplay.swc created when this FLA is published.

flex 4 preloader

In the first frame of the FLA "actions" layer we create the functions to set the two different progress bars:

//reset
setMainProgress(0);
setInitalizeProgress(0);
loading_txt.text = "";

//function for setting main prgress bar function setMainProgress(percent:Number):void { prog_bar.width = percent * 275; }

//function for setting the initilize bar function setInitalizeProgress(percent:Number):void { initialize_bar.width = percent * 275; }

The final step is to "Publish" the FLA so that the SWC file is create, this SWC will be used in Flash Builder.

Creating the Custom Preloader in Flex 4

The first step is to place the PreloaderDisplay.swc in the "libs" folder, this will make the PreloaderDisplay and its methods available to Flex:

preloader swc libs

To define a custom preloader we will do this in the Flex application's Application file, we simply specify the preloader class:

<s:Application preloader="com.themorphicgroup.preload.Preloader" ...

In the Preloader class we will extend "SparkDownloadProgressBar". The SparkDownloadProgressBar class displays download progress.
From Flex 4 docs: It is used by the Preloader control to provide user feedback while the application is downloading and loading. The download progress bar displays information about two different phases of the application: the download phase and the initialization phase.

The Preloader.as extends "SparkDownloadProgressBar" and we will use the FLA PreloaderDisplay.swc by creating a variable called "preloaderDisplay":

public class Preloader extends SparkDownloadProgressBar {
	private var preloaderDisplay:PreloaderDisplay;
	...

To add the PreloaderDisplay we will override the SparkDownloadProgressBar's "createChildren" method, in this method we will create a new PreloaderDisplay and use the "addChild" method (SparkDownloadProgressBar inherits addChild from DisplayObjectContainer):

override protected function createChildren():void
{
	if (!preloaderDisplay) {
		preloaderDisplay = new PreloaderDisplay();
		
		var startX:Number = Math.round((stageWidth - preloaderDisplay.width) / 2);
		var startY:Number = Math.round((stageHeight - preloaderDisplay.height) / 2);
		
		preloaderDisplay.x = startX;
		preloaderDisplay.y = startY;
		addChild(preloaderDisplay);
	}
}

There are several methods that will override so that we can make updates to the PreloaderDisplay.swc. The rslProgressHandler method will be called each time a RSL is being loaded. We will use this method to set text indicating the current count of RSL being loaded:

private var rslBaseText:String = "loading: ";
override protected function rslProgressHandler(evt:RSLEvent):void {
	if (evt.rslIndex && evt.rslTotal) {
		//create text to track the RSLs being loaded
		rslBaseText = "loading RSL " + evt.rslIndex + " of " + evt.rslTotal + ": ";
	}
}

The next method we will override is setDownloadProgress. This method indicates the current download progress. in this method we will set the PreloaderDisplay.swc main progress bar and set the text:

override protected function setDownloadProgress(completed:Number, total:Number):void {
	if (preloaderDisplay) {
		//set the main progress bar inside PreloaderDisplay
		preloaderDisplay.setMainProgress(completed/total);
		//set percetage text to display, if loading RSL the rslBaseText will indicate the number
		setPreloaderLoadingText(rslBaseText + Math.round((completed/total)*100).toString() + "%");
	}
}

Finally we will look at overriding setInitProgress, this method indicates the progress of the Flex app as it initializes. We will set the text in PreloaderDisplay.swc and change the progress of the second initialize progress bar:

override protected function setInitProgress(completed:Number, total:Number):void {
	if (preloaderDisplay) {
		//set the initialization progress bar inside PreloaderDisplay
		preloaderDisplay.setInitalizeProgress(completed/total);
		//set loading text
		if (completed > total) {
			setPreloaderLoadingText("almost done");
		} else {
			setPreloaderLoadingText("initializing " + completed + " of " + total);
		}
	}
}

 

This blog entry does not cover every bit of code used in the preloader, so View Demo Preloader App right click for source view

 

Example of Feature Rich Item Renderers in Flex 4

This is an example of creating feature rich item renderers in Flex 4. The example retrieves this blog's RSS feed and displays each entry in a list. This example will demonstrate:

  • Skinning and item renderer
  • States in an item renderer
  • Pass callback function into item renderer
  • Override ItemRenderer 'set data' have data as a known ValueObject
  • Swap icons/images based on data values


 View the Example with source view enabled

This blog post will cover the main points of the example but not the entire code, so view the example's source view to see all the code in full.

Getting Blog Entries From RSS

I won't go into too much detail about how the data is retrieved, view the source for all the details. The RSSService class makes a request to this blog's RSS url. That XML responce is turned into an ArrayCollection of BlogEntryVO value objects. The result ArrayCollection is set as the data provider for the Spark List.

Skinning the Spark List

Spark List: The first step in skinning the Spark List is to define the 'skinClass':


<s:List id="blogList"
    skinClass="com.themorphicgroup.skins.list.ListSkin"
    change="blogList_selectionHandler(event)"
    caretChange="blogList_selectionHandler(event)" />

Skinning Spark List: Lets look at the 'com.themorphicgroup.skins.list.ListSkin' List skin class. The most important parts of this skin is the 'Scroller' and 'DataGroup' it surrounds. The DataGroup is a simple container class in Flex 4 for holding data items and item renderers. The Scroller enables the DataGroup items to be scrolled. Full List skin code:


<?xml version="1.0" encoding="utf-8"?>
<s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009"
             xmlns:s="library://ns.adobe.com/flex/spark"
             xmlns:mx="library://ns.adobe.com/flex/halo">


    <fx:Metadata>
        [HostComponent("spark.components.List")]
    </fx:Metadata>
    
    <s:states>
        <s:State name="normal" />
        <s:State name="over"/>
    </s:states>
    
    <!-- background -->
    <s:Rect top="0" right="0" bottom="0" left="0">
        <s:stroke>
            <s:SolidColorStroke color="0x999999" weight="2"/>
        </s:stroke>
        <s:fill>
            <s:SolidColor color="0xffffff" color.over="0xf8f8f8" />
        </s:fill>
    </s:Rect>
    
    <!-- scroller -->
    <s:Scroller id="scroller"
                left="0"
                top="0"
                right="0"
                bottom="0"
                horizontalScrollPolicy="off"
                minViewportInset="1"
                focusEnabled="false">

        
        <!-- container for data-->
        <s:DataGroup id="dataGroup">
            <s:layout>
                <s:VerticalLayout gap="0" horizontalAlign="contentJustify" />
            </s:layout>
        </s:DataGroup>
        
    </s:Scroller>
    
</s:SparkSkin>

Skinning Spark List and global vertical scrollers: The last thing we will look at in skinning the List is the skin for the Scroller (VScroll). The skin classes for the scroller are in com.themorphicgroup.skins.scroller.vertical To define the 'VerticalScrollbar' Skin to all Spark VScrollBar we do that in the css file:


s|VScrollBar {
    skinClass: ClassReference("com.themorphicgroup.skins.scroller.vertical.VerticalScrollbar");
}

Define an ItemRenderer for the Spark List

In creationComplete we will create the item renderer for the Spark List, we will also define any needed properties. In this case we want to pass in a callback funtion for when the delete icon is clicked in an item renderer.


//create itemrenderer
protected function application_creationCompleteHandler(event:FlexEvent):void {
    //create itemrenderer
    blogListItemRenderer = new ClassFactory(BlogEntryItemRenderer);
    //define properties (callback for item delete)
    blogListItemRenderer.properties = {deleteHandlerFunction:itemDeleteClick_handler};
    //set itemrenderer to List
    blogList.itemRenderer = blogListItemRenderer;
    .... }

//callback function for delete click
private function itemDeleteClick_handler(blogEntryItem:BlogEntryVO):void {
    ...

Inside the Item Renderer when the delete icon is clicked the callback function is passed the current item renderer's data (a value object):


public var deleteHandlerFunction:Function;
private function trash_btn_clickHandler(event:MouseEvent):void {
    //callback function pass BlogEntryVO value object
    deleteHandlerFunction(blogEntry);
}

The ItemRenderer

Setting data in the ItemRenderer: In the 'BlogEntryItemRenderer' we will override the the set data function and set a BlogEntryVO with the data of the item renderer:


private var blogEntry:BlogEntryVO

override public function set data(value:Object):void {
    super.data = value;
    if (value is BlogEntryVO) {
        blogEntry = BlogEntryVO(value);
    }
}

Displaying data in the ItemRenderer: To display the data values in the itemrenderer we will override updateDisplayList and set values to Labels etc:


override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
    super.updateDisplayList(unscaledWidth,unscaledHeight);
    
    if (title_lbl) {
        title_lbl.text = blogEntry.title;
        ...

Skinning and States in the ItemRenderer

To make the item renderer more attractive and interactive we will create some states. In Flex 4 you can specify not only the name of a state but a name that will define a group of states:


<s:states>
    <s:State name="normal" />
    <s:State name="hovered" stateGroups="[hoveredStates]" />
    <s:State name="selected" stateGroups="[selectedStates]" />
    <s:State name="normalAndShowsCaret" />
    <s:State name="hoveredAndShowsCaret" stateGroups="[hoveredStates]" />
    <s:State name="selectedAndShowsCaret" stateGroups="[selectedStates]" />
</s:states>

Having the state and stateGroups names means we can define properties for those states. For example with can set the alpha of the background color as alpha='0' and them the when we are in one of the hovered states as alpha.hoveredStates='.1':


<s:Rect width="100%" height="100%">
    <s:fill>
        <s:SolidColor color="0x6699cc" alpha="0" alpha.hoveredStates=".1" alpha.selectedStates=".25" />
    </s:fill>
</s:Rect>

<s:Label id="title_lbl"
         maxDisplayedLines="1"
         styleName="myriad"
         left="10"
         top="10"
         right="26"
         textDecoration.hoveredStates="underline"
         fontWeight.selectedStates="bold"
         color="#000000"
         fontSize="14"/>

Summary

This blog post does not cover every bit of code in the example so View the Example with source view enabled.

Example of Feature Rich Dynamic Item Renderers in Flex 3

In the last Flex 3 rich feature item renderer example we looked at item renderers that had some nice visual and functional features, in this example we will take it to the next step and introduce some dynamic abilities to the item renderers. By using dynamic item renderers you can create more flexible & reusable itemrenderers, you can also do neat stuff like pass callback functions to handle events in the itemrenderer.

Here are some of the things this dynamic item renderer example will demonstrate:

  • Reuse the same item renderer for a DataGrid and a List, each with a different data provider
  • Pass delete/click function into item renderer
  • Dynamically change icons
  • Dynamically change the label function
  • Set label title style


View Example (right click for source)

In this post we won't go over every detail of the code, so check out the source in the example.

To start of with the basics, here is how to setup a itemrenderer using ClassFactory:

private var personItemRendererFactory:ClassFactory;
private function onInitialize():void {
	personItemRendererFactory = new ClassFactory(MyItemRenderer);
	peopleColumn.itemRenderer = personItemRendererFactory;
}
...
<mx:DataGrid id="peopleDataGrid" dataProvider="{peopleDataProvider}">
	<mx:columns>
		<mx:DataGridColumn id="peopleColumn" />
	</mx:columns>
</mx:DataGrid>

The example above doesn't really do much more than setting in itemrenderer in the DataGrid tag itself would, so lets set a property of the itemrenderer:

private function onInitialize():void {
	personItemRendererFactory = new ClassFactory(MyItemRenderer);
	personItemRendererFactory.properties = {doStuff: true};
	peopleColumn.itemRenderer = personItemRendererFactory;
}

In the above example we are now creating an itemrenderer and setting the 'doStuff' property using the ClassFactory properties object. Using the class factory properties we can set many things at once including functions. Let's say we want to listen for a click event inside the itemrenderer we can pass in a callback function that gets called from the item renderer when clicked:

private function onInitialize():void {
	personItemRendererFactory = new ClassFactory(MyItemRenderer);
	personItemRendererFactory.properties = {clickFunction: itemrendererClick_handler};
	peopleColumn.itemRenderer = personItemRendererFactory;
}

private function itemrendererClick_handler(evt:MouseEvent):void { Alert.show('clicked'); }

/* this in item renderer */ //inside the itemrenderer we need to define the click function public var clickFunction:Function;

//and then for this example lets call the clickFunction when the canvas is clicked <mx:Canvas click="clickFunction(event)"...

The above example allows a function to set on the itemrenderer. When the itemrenderer is clicked the event is handled in the same component that the holds DataGrid, this can be very convenient.

When using the properties of ClassFactory there is a something to be aware of; your itemrenderer may require a property to be set, but the ClassFactory and properties will not enforce that property to be required. For example if a click handler function is required in the ItemRenderer but not set in the properties there will be a runtime error when the ItemRenderer is clicked.

View the example and right click for source to see more details on how to do things like dynamically change icons and label functions.
View Example (right click for source)

This example is not intended to be a best practices for the most efficient item renderers, for further reading: Efficient Item Renderers, Advanced visual components

Using Gumbo and itemRendererFunction to create multiple ItemRenderers

Gumbo has added an "itemRendererFunction" function that allows certain data containers to specify an itemRenderer based on the data item. In this example an FxDataContainer's dataProvider is set to an ArrayCollection that contains 2 different types of Value Objects. Depending on the type of Value Object the itemRendererFunction returns a different itemRenderer.


View Example (right click for source)

In this example there are two different Value Objects: PhotoVO and QuoteVO. An FxDataContainer's dataProvider is set to an ArrayCollection:

[Bindable]private var VODataProvider:ArrayCollection;

<FxDataContainer dataProvider="{VODataProvider}"...

The ArrayCollection is populated with 5 Value Objects, 2 PhotoVO and 3 QuoteVO.

In the FxDataContainer the itemRendererFunction is set to a function:

<FxDataContainer dataProvider="{VODataProvider}" 

itemRendererFunction="itemRendererFunction_handler"

In the itemRendererFunction a ClassFactory is passed back based on the type of data item in the itemRenderer. In this example there is a different itemRenderer for the PhotoVO and QuoteVO. We will also pass in a function to the itemRenderer to handle clicks:

private function itemRendererFunction_handler(item:Object):ClassFactory {

var classFactory:ClassFactory;

if (item is PhotoVO) {

//item is PhotoVO so use Photo ItemRenderer

classFactory = new ClassFactory(PhotoItemRenderer);

} else if (item is QuoteVO) {

//item is QuoteVO so use Quote ItemRenderer

classFactory = new ClassFactory(QuoteItemRenderer);

}

//pass callback click function

classFactory.properties = {clickFunction:itemRenderClick_handler};

return classFactory;

}

View Example with source enabled (flash 10 required)

Gumbo and Catalyst Photo Viewer Application

I've posted an example of a Flex application created with the MAX preview versions of Flash Catalyst and Gumbo. This small demo application was created to test out some of the new features in both Catalyst and Gumbo. It is not a perfect project, but a starting point for further projects.

Gumbo Catalyst Photo Application
View Example (right click for source)

The main goal of this project was to play with the new features in Catalyst and Gumbo using a close to real world example application, here is what was done:

  • Start with a photoshop layout (PhotoShop file located in PSD directory)
  • Use Catalyst to layout/components/skins and export FXG project
  • Import FXG to Gumbo project
  • In Gumbo add data/photo/etc functionality to the project
  • Take project back to Catalyst for small visual edits, then back to Gumbo
  • Use new Gumbo MXML tags/components
  • Play with new __AS3__.vec.Vector (using the new BitmapData.histogram)

Instead of detailing every step of the process there is great Gumbo Documentation and Catalyst Examples.

View Catalyst and Gumbo Photo Application (requires Flash 10 player)

Example of Feature Rich ItemRenderers in Flex

(Related: see entry on Feature Rich Dynamic Item Renderers)

In response to some requests I got from friends wanting some more real world ItemRenderer examples, here is one that approaches the item renderer from a graphical approach and brings together some different techniques to create a nicely featured ItemRenderer.

Here is what this example DataGrid/ItemRender demonstrates:

  • MXML based ItemRenderer
  • Override ItemRenderer 'set data' have data as a known ValueObject
  • Swap icons/images based on data values
  • Highlight selected ItemRenderer
  • Enable ItemRenderer to dispatch an event to remove a person from the grid

DataProvider and ValueObjects
The first thing we'll look at in the example is the data and data provider for the Grid. Keep in mind this is just a quick demo way to load sample data, the goal is to create an ArrayCollection of Value Objects. The sample XML data is loaded via an HTTPService. When the result comes back from the service we cast the result as an ArrayCollection, we then loop through each item in that result ArrayCollection. Each item is an Object containing the 'person' data defined in the XML. For this example we want to place each person data in a person ValueObject (VO). This VO provides a known data type that we will use as the 'data' in the ItemRenderer. Often when using AMF taking to ColdFusion/BlazeDS/Java/Etc the VO will be aliased to a data type on the server, so this example simulates the DataGrid provider being an ArrayCollection of VOs.
This result function populates the DataProvider with our Person VOs:


private function httpResult_handler(evt:ResultEvent):void {
    if (evt.result.people.person) {
        //result

        var resultAC:ArrayCollection = evt.result.people.person as ArrayCollection;
        //loop through each item in data

        for (var i:int=0;i<resultAC.length;i++) {
            //create person VO

            var person:Person = new Person();
            //add data

            person.fill(resultAC[i]);
            //add person to main data provider

            peopleDataProvider.addItem(person);
        }
    }
}

ItemRenderer and Override of 'set data'
Next we'll look at how the data is dealt with inside the ItemRenderer. The DataGrid's only column is set to have an ItemRenderer. When the DataProvider is populated the DataGrid is going to set the 'data' property on each row's ItemRenderer with the the associated VO in the DataProvider ArrayCollection. We want to make sure that the data inside the ItemRenderer is actually a Person VO object (not a generic Object), so we need to override the 'set data' function. When we override this function we are now able to cast the data value as a Person VO. This will allow us to refer to data inside the ItemRenderer as that VO with known attributes rather than a generic Object that it would otherwise be:


[Bindable]private var person:Person;
override public function set data(value:Object):void {
    super.data = value;
    if (value is Person) {
        person = Person(value);
    }
}

When overriding the set data function make sure to remember set 'super.data=value'. The ItemRenderer still needs to know the value of the data otherwise it will be treated like an empty row in the DataGrid.

Swap ItemRenderer Images Based on Data
As a nice UI feature let's display a male/female icon based on the person's gender. This is easy to do, we know the data will be a Person VO. So we can have the Image component ask for the correct image based on the 'person.gender' value:


<mx:Image id="gender_img" source="{getGenderImg(person.gender)}"...

Since the person variable is Bindable if there is a change the 'getGenderImg' function will be asked to give the image its source:


private function getGenderImg(gender:String):Class {
    if (gender == Person.GENDER_FEMALE) {
        return imgUserFemale;
    } else {
        return imgUserMale;
    }
}

Highlight Selected ItemRenderer
Next let's add some nice functionality to make the ItemRenderer stand out a little more when it is selected. To do this we need to override another function. This time we're going to override the updateDisplayList function, this will allow us to set some styles and graphical elements to the ItemRenderer is if is the selected itemRenderer. Using 'ListBase' we are able to find out if the 'owner' (the DataGrid) has this data selected:


override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
    super.updateDisplayList(unscaledWidth, unscaledHeight);
    if(ListBase(owner).isItemSelected(data)) {
        name_lbl.setStyle("styleName","pnameselected");
        selected_img.visible = true;
    } else {
        name_lbl.setStyle("styleName","pname");
        selected_img.visible = false;
    }
}

Enable ItemRenderer to dispatch a remove person event
Lastly we'd like the trash can icon to remove a the person when clicked. There are other (maybe more preferable, but that's for a different example) methods, but for this example let's have the ItemRenderer dispatch an event and have a listener set to catch that event. On the click event of the trash can icon there is an event dispatched:


public static const DELETE_PERSON_EVENT:String = "deletePerson";
private function deleteClick_handler():void {
    var dEvt:Event = new Event(DELETE_PERSON_EVENT,true);
    this.dispatchEvent(dEvt);
}

This 'deletePerson' event is dispatched by the ItemRenderer and importantly has 'bubbles' set to true. This bubbling enables the parent component to simply add a listener for the event:


myDG.addEventListener(PersonItemRenderer.DELETE_PERSON_EVENT,deletePerson_handler);
private function deletePerson_handler(evt:Event):void {
    if (myDG.selectedIndex != -1)
        peopleDataProvider.removeItemAt(myDG.selectedIndex);
}

That's it for this example. The next example will build on this but go the route of a dynamic ItemRenderer, while they a little bit more complicated can be very flexible allowing for dynamic properties to be set on the itemRenderers.
View the Example

NorCal Flex User Group hosts Ryan Stewart

If you're in the Sacramento area come to the NorCal Flex User group January 23rd to see Ryan Stewart talk about Flex 3 and AIR.

meeting details