Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development

Effortless Flex 4 Development: Item Renderers

Many of the data-driven components, including List, ComboBox, DropDownList, Tree, DataGrid, and AdvancedDataGrid, can use item renderers to control how data is displayed. In this excerpt from Effortless Flex 4 Development, Larry Ullman shows you how to work with item renderers.
From the book

Item Renderers

Many of the data-driven components, including List, ComboBox, DropDownList, Tree, DataGrid, and AdvancedDataGrid, can use item renderers to control how data is displayed. Whereas a labelFunction can customize the displayed information, an item renderer acts more like a template, and allows you to display more than just a string.

Item renderers can be written in ActionScript or MXML, but I'll use MXML here to make the discussion most approachable. For the example, I'm going to (egotistically) list a few of the books I've written. To start, I've got the following ArrayList of information about the books:

private var myBooks:ArrayList = new ArrayList([
{title: 'PHP 6 and MySQL 5 for Dynamic Web Sites', year: 2008, image:
'../assets/php6mysql5.png'},
{title: 'Adobe AIR with Ajax', year: 2008, image: '../assets/air.png'},
{title: 'Ruby', year: 2009, image: '../assets/ruby.png'}
]);

I can easily display each title in a List like so (Figure 6.7):

<s:List dataProvider="{myBooks}" labelField="title" />

If I want to display the title and publication year, I could make use of a label function:

<s:List dataProvider="{myBooks}" labelFunction="formatListLabel" />
private function formatListLabel(item:Object):String {
   return item.title + ' (' + item.year + ')';
}

But if I wanted to also display the image, I can't do that using a label function, as such functions only return strings. The alternative is to use an item renderer. An item renderer allows me to specify the components and formatting to use to display an individual item. This is how I might want each item to be displayed using components:

<s:HGroup gap="5">
   <mx:Image source="image" />
   <s:Label text="title" fontSize="16" />
   <s:Label text="(year)" fontSize="12" />
</s:HGroup>

That combination of components, wrapped within an HGroup, will give me the layout shown in Figure 6.8. Certainly you could do more to make this look fancy, but this is already so much more elaborate than what can be accomplished using a label function.

In those components, the image, title, and year values need to come from the individual item being displayed. Within item renderers, the currently rendered item will automatically be available through an object named data. So the item renderer template can actually be defined as

<s:HGroup gap="5">
   <mx:Image source="{data.image}" />
   <s:Label text="{data.title}" fontSize="16" />
   <s:Label text="({data.year})" fontSize="12" />
</s:HGroup>

There are three places you can define this renderer so that it's usable by a component: in an external file, in the Declarations section, and inline. I'll demonstrate each separately. Note that over the next several pages, I'll create an item renderer to be used with a List component. After those demonstrations, I'll briefly discuss how item renderers to be used by other components will differ.

External Item Renderers

Here are the steps you would take to define an item renderer in an external file:

  1. Create a new, MXML file.
  2. Add the XML declaration:
    <?xml version="1.0" encoding="utf-8"?>
    All XML documents should begin with this.
  3. Create an opening ItemRenderer tag:
    <s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
              xmlns:s="library://ns.adobe.com/flex/spark"
              xmlns:mx="library://ns.adobe.com/flex/mx">
    The ItemRenderer component is defined in Spark. In its opening tag, you should declare the namespaces, just as you do in the primary MXML file's Application tag. This is necessary so that this file can reference components such as Image and Label, defined in the Halo and Spark namespaces.
  4. Define the item renderer:
    <s:HGroup gap="5" paddingTop="15">
       <mx:Image source="../assets/{data.image}" />
       <s:Label text="{data.title}" fontSize="16" />
       <s:Label text="({data.year})" fontSize="12" />
    </s:HGroup>
    This code is exactly as you've already seen it, save for the addition of the paddingTop property. As the renderer will be used by multiple, subsequent items, I want to create a gap between each, accomplished using paddingTop (you could also use paddingBottom). Conversely, the HGroup's gap property creates a five-pixel gap among the children of the HGroup: the Image, Label, and Label.
  5. Close the ItemRenderer tag:
    </s:ItemRenderer>
  6. Save the file in your project's directory.

    I would recommend using the backwards domain naming scheme, first introduced in Chapter 3, "ActionScript You Need to Know." My company's name is DMC Insights, so I would create, within the src folder, a com folder. Within that I would create a dmcinsights folder. Within that folder, I would save this file as BookListRenderer.mxml (Figure 6.9).

    Alternatives would be to store the file in src/components/renderers or src/views/renderers. It's really a matter of personal preference how you organize these files; just choose a route that makes sense to you.

To use the item renderer, add itemRenderer=" path/to/renderer" to the List tag in the primary MXML file. Assuming the renderer is stored in src/com/dmcinsights/BookListRenderer.mxml, you would use

<s:List dataProvider="{myBooks}" itemRenderer="com.dmcinsights.
BookListRenderer">

Note that you just use the basename of the file as the name of the renderer, without the .mxml extension. Figure 6.10 shows the same List as in Figure 6.7, now using the item renderer.

Declared Item Renderers

If you'd rather not separate out your renderer definition from the application that uses it, you can define a renderer in the primary MXML file. As the renderer is a non-visual component (on its own, that is; it's used by a visual component), you would create it within the Declarations section. To do so, you still make use of the ItemRenderer tags, but you don't need to include the namespace declarations, as the file already has those. But ItemRenderer element must be wrapped within a Component element, defined in the fx namespace. This element is used to define your own components. You use its className property to assign a unique class identifier (i.e., name) to the made-up component. Here, then, is the same renderer defined in the Declarations section:

<fx:Declarations>
<fx:Component className="BookListRenderer">
   <s:ItemRenderer>
      <s:HGroup gap="5" paddingTop="15">
         <mx:Image source="{data.image}" />
         <s:Label text="{data.title}" fontSize="16" />
         <s:Label text="({data.year})" fontSize="12" />
      </s:HGroup>
   </s:ItemRenderer>
</fx:Component>
</fx:Declarations>

You'll note that the renderer still uses the data object to reference individual values.

To use this renderer in a component, identify it with the itemRenderer property:

<s:List dataProvider="{myBooks}" itemRenderer="BookListRenderer">

In this case, as the renderer is defined within the same application file, you don't need to provide any reference to it such as com.dmcinsights.

Inline Renderers

The third way to define renderers is inline. Just as you can declare a data source within a component, you can also declare a renderer within a component. When you do so, you don't use the itemRenderer property in the opening tag. Instead, use opening and closing itemRenderer tags within the component, where the definition will take place. As with defining a renderer in the Declarations, you don't need to include the namespace declarations, but you do need to wrap the renderer within Component. Here's the same List:

<s:List dataProvider="{myBooks}">
   <s:itemRenderer>
      <fx:Component>
         <s:ItemRenderer>
            <s:HGroup gap="5" paddingTop="15">
               <mx:Image source="{data.image}" />
               <s:Label text="{data.title}" fontSize="16" />
               <s:Label text="({data.year})" fontSize="12" />
            </s:HGroup>
         </s:ItemRenderer>
      </fx:Component>
   </s:itemRenderer>
</s:List>

Drop-In Item Renderers

Another way you can work with item renderers is by using so-called drop-in renderers, which is to say using another Flex component as the renderer. For example, a DataGridColumn uses a Label as its renderer by default. Figure 6.11 shows how my list of books would be displayed in a DataGrid without any customization of the renderers.

Logically, instead of showing the name of the image, I would want to show the image itself. To simply accomplish this, just tell the DataGridColumn to use an Image component as its renderer (Figure 6.12):

<mx:DataGrid dataProvider="{myBooks}" rowHeight="50">
  <mx:columns>
    <mx:DataGridColumn dataField="image" itemRenderer=
    "mx.controls.Image" />
    <mx:DataGridColumn dataField="title" />
    <mx:DataGridColumn dataField="year" />
  </mx:columns>
</mx:DataGrid>

Comparing Component Renderers

Except for the preceding example of a drop-in renderer used by a DataGridColumn, the item renderers created in this section were all used by a List component. In every case, the renderer was defined within s:ItemRenderer tags. When creating renderers for a ComboBox or a DropDownList, you would still want to use the ItemRenderer tags. However, the ComboBox and DropDownList components can only display a single line of text for each element, so you're pretty much restricted to using the Label and RichText components in the renderers. But you can still do more using, say, RichText in a renderer than you can just using a label function. Note the following example (Figure 6.13):

<s:DropDownList dataProvider="{myBooks}" width="400">
   <s:itemRenderer>
      <fx:Component>
        <s:ItemRenderer>
          <s:RichText>
            <s:textFlow>
              <s:TextFlow>
                <s:span fontSize="16">{data.title}</s:span>
                <s:tab/><s:span fontStyle="italic" fontSize=
                "12">{data.year}</s:span>
              </s:TextFlow>
            </s:textFlow>
          </s:RichText>
        </s:ItemRenderer>
     </fx:Component>
   </s:itemRenderer>
</s:DropDownList>

An item renderer to be used by a Tree is defined within MXTreeItemRenderer tags. It makes use of view states, a topic to be discussed in Chapter 11, "Improving the User Experience."

The DataGrid and AdvancedDataGrid components have MXDataGridItemRenderer and MXAdvancedDataGridItemRenderer tags for defining renderers. You can use multiple components within these renderers, including non-text ones. However, you should add top, bottom, left, and right properties to the renderer components in order to absolutely position them within each cell.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020