http://www.adobe.com/cn/devnet/flex/articles/itemrenderers_pt2.html
In Part 1 of this series I showed you how to make an inline itemRenderer—that is, an itemRenderer whose MXML tags and ActionScript code are in the same file as the list using the itemRenderer. The code is inline with the rest of the code in the file.
You'll also recall that I said you should think of inline itemRenderers are being separate classes. The Flex compiler in fact extracts that inline code and makes a class for you. The benefit of inline itemRenderers is that the code is in the same place as the list, but that's also a drawback when the itemRenderer becomes complex. What I'm going to show you in this article is how to make the class yourself.
Extracting the itemRenderer into an external file has several benefits:
- The itemRenderer can easily be used in multiple lists
- The code is easier to maintain
- You can use Flex Builder's Design View to sketch out the initial itemRenderer
This series includes the following articles:
- Part 1: Inline renderers
- Part 2: External renderers
- Part 3: Communication
- Part 4: States and transitions
- Part 5: Efficiency
An MXML itemRenderer
In Part 1 you saw there was a complex itemRenderer used for a DataGrid:
<mx:DataGridColumn headerText="Title" dataField="title"> <mx:itemRenderer> <mx:Component> <mx:HBox paddingLeft="2"> <mx:Script> <![CDATA[ override public function set data( value:Object ) : void { super.data = value; var today:Number = (new Date()).time; var pubDate:Number = Date.parse(data.date); if( pubDate > today ) setStyle("backgroundColor",0xff99ff); else setStyle("backgroundColor",0xffffff); } ]]> </mx:Script> <mx:Image source="{data.image}" width="50" height="50" scaleContent="true" /> <mx:Text width="100%" text="{data.title}" /> </mx:HBox> </mx:Component> </mx:itemRenderer> </mx:DataGridColumn>
The itemRenderer is based on an HBox, contains an Image and a Text, and the background color is set according to the pubDate
field
of the item record. You can write this same itemRenderer as an external file using these steps:
-
If you are using Flex Builder, create a new MXML Component file (I've named mine GridColumnSimpleRenderer, but use whatever you like) and set the root tag to be
HBox
. Don't worry about the size. -
If you are using the SDK alone, create a new MXML file (call it GridColumnSimpleRenderer.mxml) and set the root tag to be
HBox
. -
With the file open, copy everything between
<mx:HBox>
and</mx:HBox>
, but do not copy those tags, since they are already in the file. The result should look something like this:
<?xml version="1.0" encoding="utf-8"?><mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300"><mx:Script><![CDATA[override public function set data( value:Object ) : void {super.data = value;var today:Number = (new Date()).time;var pubDate:Number = Date.parse(data.date);if( pubDate > today ) setStyle("backgroundColor",0xff99ff);else setStyle("backgroundColor",0xffffff);}]]></mx:Script><mx:Image source="{data.image}" width="50" height="50" scaleContent="true" /><mx:Text width="100%" text="{data.title}" /></mx:HBox>
- Save the file.
Now modify the DataGridColumn definition by removing the inline itemRenderer and replacing it with this:
<mx:DataGridColumn
headerText="Title" dataField="title"itemRenderer="GridColumnSimpleRenderer">
Determining an itemRenderer's width and height
The List control always sets the itemRenderer's width. In this example, the explicit width="400"
is
ignored. You should write your itemRenderer to assume the width will change as the user changes the column or list's width.
The height is a different matter. If the list has an explicit rowHeight
set,
it will impose that height on each row, ignoring any height you've set on the itemRenderer. However, if you set the list's variableRowHeight
property
to true
,
then the list will seriously consider the itemRenderer's height. In this example, the height is explicitly set to 300, so each row is 300 pixels high.
To fix this, remove the explict height from the itemRenderer file and the application will work correctly.
Dynamically Changing the itemRenderer
In this example the set
data()
function has been overridden to examine the data and set the itemRenderer's backgroundColor
.
This is very common. Overriding set
data()
enables you to intercept the time when the data is being changed for a new row and you can you make style changes.
Common mistakes are:
-
Forgetting to call
super.data = value;
. This is VITAL—failure to do this will really mess up your itemRenderer. -
Forgetting to reset the style(s) if any tests fail. It might be tempting to just set the color when the
pubDate
is in the future, but you have to remember that itemRenderers are recycled, and so theelse
statement is very necessary.
An ActionScript itemRenderer
Now you'll write another itemRenderer, this time using an ActionScript class. In the previous article there is a TileList with this inline itemRenderer:
<mx:itemRenderer><mx:Component><mx:HBox
verticalAlign="top"><mx:Image source="{data.image}" /><mx:VBox height="115" verticalAlign="top" verticalGap="0"><mx:Text text="{data.title}" fontWeight="bold" width="100%"/><mx:Spacer height="20" /><mx:Label text="{data.author}" /><mx:Label text="Available
{data.date}" /><mx:Spacer height="100%" /><mx:HBox width="100%" horizontalAlign="right"><mx:Button label="Buy" fillColors="[0x99ff99,0x99ff99]"><mx:click><![CDATA[var e:BuyBookEvent = new BuyBookEvent();e.bookData = data;dispatchEvent(e);]]></mx:click></mx:Button></mx:HBox></mx:VBox></mx:HBox></mx:Component></mx:itemRenderer>
You'll make that into an ActionScript external itemRenderer. You'll need to follow these steps:
- Create a new ActionScript class. Call it BookTileRenderer.as and make it extend HBox, just like the inline itemRenderer.
package{import
flash.events.MouseEvent;import mx.containers.HBox;import mx.containers.VBox;import mx.controls.Button;import mx.controls.Image;import mx.controls.Label;import mx.controls.Spacer;import mx.controls.Text;public class BookTileRenderer extends HBox{public function
BookTileRenderer(){super();}}}
- Create member variables to hold the references to the child components.
private
var coverImage:Image;private var titleText:Text;private var spacer1:Spacer;private var authorLabel:Label;private var pubdateLabel:Label;private var spacer2:Spacer;private var buyButton:Button;
-
Override the
createChildren()
function to create the child components and add them to the HBox.
override
protected function createChildren():void{coverImage = new Image();addChild(coverImage);var innerBox:VBox = new VBox();innerBox.explicitHeight = 115;innerBox.percentWidth = 100;innerBox.setStyle("verticalAlign","top");innerBox.setStyle("verticalGap", 0);addChild(innerBox);titleText
= new Text();titleText.setStyle("fontWeight","bold");titleText.percentWidth = 100;innerBox.addChild(titleText);spacer1 = new Spacer();spacer1.explicitHeight = 20;innerBox.addChild(spacer1);authorLabel = new Label();innerBox.addChild(authorLabel);pubdateLabel
= new Label();innerBox.addChild(pubdateLabel);spacer2 = new Spacer();spacer2.percentHeight = 100;innerBox.addChild(spacer2);var buttonBox:HBox = new HBox();buttonBox.percentWidth = 100;buttonBox.setStyle("horizontalAlign","right");innerBox.addChild(buttonBox);buyButton
= new Button();buyButton.label = "Buy";buyButton.setStyle("fillColors",[0x99ff99,0x99ff99]);buyButton.addEventListener(MouseEvent.CLICK, handleBuyClick);buttonBox.addChild(buyButton);}
I've indented the code to show the parent-child relationships. Also, make sure you include an event listener on the Buy button.
-
Override the
commitProperties()
function and set the user interface controls from the data.
override
protected function commitProperties():void{super.commitProperties();coverImage.source = data.image;titleText.text = data.title;authorLabel.text = data.author;pubdateLabel.text = data.date;}
- Add the click event handler for the Buy button.
private
function handleBuyClick( event:MouseEvent ) : void{var e:BuyBookEvent = new BuyBookEvent();e.bookData = data;dispatchEvent(e);}
-
Modify the TileList in the main application to use the itemRenderer ActionScript class. Simply remove the
inlineItemRenderer
and replace it with anitemRenderer
property right in the tag.
<mx:TileList
id="mylist" x="29" y="542" width="694" itemRenderer="BookTileRenderer" dataProvider="{testData.book}" height="232" columnWidth="275" rowHeight="135" >
If you are going to use an existing container class, such as HBox, I wouldn't bother doing this in ActionScript. You can see it is more complex than using an MXML file and, quite frankly, there is little performance benefit to it.
Reusable itemRenderers
Here's an example of an itemRenderer that displays a numeric value using the CurrencyFormatter. I call it PriceFormatter:
<?xml
version="1.0" encoding="utf-8"?><mx:Text xmlns:mx="http://www.adobe.com/2006/mxml"><mx:Script><![CDATA[import mx.controls.dataGridClasses.DataGridListData;[Bindable] private var formattedValue:String;override public function set data(value:Object):void{super.data
= value;formattedValue = cfmt.format( Number(data[(listData as DataGridListData).dataField]) );}]]></mx:Script><mx:CurrencyFormatter precision="2" id="cfmt" /><mx:text>{formattedValue}</mx:text></mx:Text>
The key to this itemRenderer is shown in red,
setting the bindable variable formattedValue
.
First, you'll see that<mx:CurrentFormatter>
was
defined as an MXML tag (you can do this in ActionScript, too, if you prefer) with an id
of cfmt
.
In the example above, the formattedValue
is
set to the result of calling the CurrentFormatter's format()
function.
The function takes a Number as its parameter type, so the value is cast to Number—that's because the dataProvider for the list is XML, and everything in XML is text; if you use a Object for your data and you have real numeric values, doing the Number cast will be harmless.
As you know, data is the property that holds the item being displayed by the itemRenderer. Using [
]
notation is another way of accessing the fields of the data item. For example, data['price']
would
be the price column. But to make this itemRenderer resuable, you cannot code for a specific field, so a more generic way is needed.
That's where listData
comes
in. All Flex components which implement the IDropInListItemRenderer interface have a listData
property.
Note: Most controls, such as Text, Label, Button, CheckBox, and so forth, implement IDropInListItemRenderer. Most containers, such as HBox, Canvas, etc. do not implement that interface. If you want to use listData
in
an itemRenderer that extends a Container, you will have to implement IDropInListItemRenderer yourself; I'll cover that in the next article.
The listData
given
to an itemRenderer contains, among other things, the rowIndex
and
the control that owns the itemRenderer—the DataGrid, List, or TileList. When you have an itemRenderer being used for the DataGrid, the listData
is
actually a DataGridListDataobject—which
includes the columnIndex and the dataField associated
with the DataGridColumn. Here's the breakdown of the statement above, starting from the inside:
-
listData as DataGridListData
—This casts the listData to a DataGridListData object so you have access to its dataField -
.dataField
—the field for the column being rendered. This is what makes this itemRenderer generic. You can use this itemRenderer for multiple columns. In this example the dataField is 'price'. -
data[ ... ]
—This accesses the data for the specific field in the item. In this example it will be the price column. -
Number( ... )
—This casts the value to a Number because the format() function requires a Number parameter. -
cfmt.format( ... )
—This formats the value as a currency.
Where to go from here
Use whatever makes you comfortable when implementing itemRenderers. Some people only work in ActionScript, which is great when you've got experience with Flex and ActionScript. MXML makes quick work of simple itemRenderers, too.
In Part 3 (coming soon) I'll discuss more communication between itemRenderers and the rest of the application.