Understand Flex itemRenderer (2)-External Renderer

Source: Internet
Author: User
Tags cdata
Document directory
  • MXML itemRenderer
  • Determines the width and height of itemRenderer.
  • Dynamically change itemRenderer
  • ActionScript itemRenderer
  • Reusable itemRenderer
  • Follow-up work

In part 1 of this series, I show you how to create the mxml tag and The ActionScript code of the itemrenderer, such as the itemrenderer, in the same file as the list using the itemrenderer. The code is inline with other code in the file.

You should remember that I said that the inline itemrenderer should be treated as a separate class. In fact, the flex compiler extracts these Inline code and creates classes for you. The advantage of inline itemrenderer is that the Code is located in the same position as the list, but this becomes a disadvantage if itemrenderer becomes complicated. In this article, I will show you how to create a class by yourself.

Extracting itemrenderer to an external file has the following advantages:

  • ItemRenderer can be easily used in multiple lists
  • Easier code Maintenance
  • You can use the "design" view of Flex Builder to draft the initial itemRenderer.
Mxml itemrenderer

In section 1st, you can see a complicated itemrenderer used for the 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>          

Itemrenderer is based on hbox and contains an image and a text file.pubDateField to set the background color. You can use the following steps to compile the same itemrenderer into an external file:

  1. If you use Flex Builder, create a new MXML Component file (I name my fileGridcolumnsimplerenderer, You can name it at will), set the root flagHBox. Don't worry about the size.
  2. If you only use the SDK, create a new MXML file (name itGridcolumnsimplerenderer. mxml), Set the root flagHBox.
  3. When the file is opened, copy<mx:HBox>And</mx:HBox>But do not copy the tags because they exist in the file. The result should be as follows:

    <?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>
  4. Save the file.

Modify the definition of the datagridcolumn by deleting the inline itemrenderer and replacing it with the following:

<mx:DataGridColumn headerText="Title" dataField="title"itemRenderer="GridColumnSimpleRenderer">

Run the application now. You will be surprised. Because the row is very high. This is becauseheight="300".

Determines the width and height of itemrenderer.

The list control always sets the width of itemrenderer. In this example, the explicitwidth="400". You should write your own itemRenderer. If you change the column or the width of the list, it will change.

Height is another thing. If the list is explicitly setrowHeightIt will add this height to each row and ignore any height you set for itemRenderer. However, if youvariableRowHeightSet propertytrueThe height of itemRenderer is carefully considered in the list. In this example, the height is clearly set to 300, so the behavior is 300 pixels High.

To fix it, delete the clear height from the itemRenderer file to run the application correctly.

Dynamically change itemrenderer

This example overwritesset data()Function to check the data and set the itemRendererbackgroundColor. This is very common. Overwriteset data()This allows you to intercept the time when data is changed for a new row and make style changes.

Common Errors:

  • Forgot to callsuper.data = value;. This is a fatal error-it will mess up the itemRenderer.
  • Forgot to reset the style (if any test fails ). WhenpubDateIt may be tempting to set only the color when it comes to future, but you must remember that itemrenderer is used cyclically, soelseStatement is necessary.
ActionScript itemrenderer

Now, you will write another itemRenderer. This time, you will use the ActionScript class. In the previous article, there was a TileList containing 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 will convert it into an external itemRenderer of ActionScript. Follow these steps:

  1. Create an ActionScript class. Name itBooktilerenderer.And make it expand hbox, just like 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();}}}
  2. Create a member variable to store references to 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;
  3. OverwritecreateChildren()Function to create child components and add them to 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 am going to use this code to display the parent-child relationship. Make sure that the Buy button contains an event listener.

  4. OverwritecommitProperties()Function, and set user interface control 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;}
  5. Add and click the event handler function for the buy button.

    private function handleBuyClick( event:MouseEvent ) : void{var e:BuyBookEvent = new BuyBookEvent();e.bookData = data;dispatchEvent(e);}
  6. Change tilelist in the main application to the itemrenderer ActionScript class. Just deleteinlineItemRendererAnd replace it withitemRendererAttribute.

    <mx:TileList id="mylist" x="29" y="542" width="694" itemRenderer="BookTileRenderer"        dataProvider="{testData.book}" height="232" columnWidth="275" rowHeight="135" >

If you want to use an existing container class, such as HBox, I will not use ActionScript. You will find that it is more complex than using MXML files, and to be honest, there is almost no performance advantage.

Reusable itemrenderer

The following is an example of itemRenderer, which uses CurrencyFormatter to display a value. 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 part of this itemRenderer is marked in red to set variable binding.formattedValue. First, you will find<mx:CurrentFormatter>Useid cfmtIt is defined as an MXML tag (you can also use ActionScript if you want ). In the preceding example,formattedValueSet as CurrentFormatterformat()Function call result.

This function uses Number as its parameter type, so the value is converted to Number-this is because the dataProvider of the List is XML and all content in XML is text; if an Object is used for data and you have actual values, it is harmless to perform the Number transformation.

As you know, data is the property that stores the items displayed by itemRenderer. Use[ ]Mark is another way to access the data project field. For example,data['price'] Is the price column. However, to make the itemRenderer reusable, you must use a more common method instead of encoding specific fields.

At this time,listDataDebut. All Flex components that implement the IDropInListItemRenderer interface have onelistDataAttribute.

Note:Most controls such as Text, Label, Button, and CheckBox all implement IDropInListItemRenderer. Most containers such as HBox and CanvasNoImplement this interface. If you want to uselistDataYou must implement IDropInListItemRenderer by yourself. I will discuss this issue in the next article.

Provided to the itemRendererlistDataAlso includerowIndexAnd control, which has itemRenderer-DataGrid, List, or TileList. When itemRenderer is used for the DataGrid,listDataIt is actually a DataGridListData object-it contains columnIndex and dataField associated with the DataGridColumn. The following are the details of the preceding statement, starting from the internal:

  • listData as DataGridListData-It converts listdata to a datagridlistdata object so that you can access its datafield
  • .dataField-This field is used for rendering columns. It makes the itemrenderer general. You can use this itemrenderer for multiple columns. In this example, datafield is "price ".
  • data[ ... ]-It accesses the data of specific fields in the project. In this example, it is the price column.
  • Number( ... )-It converts the value to number because the format () function requires a number parameter.
  • cfmt.format( ... )-It formats the value as a currency.
Follow-up work

You can use any language you like when implementing itemRenderer. Some people only use ActionScript, Which is great if you have experience in Flex and ActionScript. MXML can also quickly create a simple itemRenderer.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.