Products
Technologies

Developer resources

How to know when an ItemRenderer is selected

Avg. Rating 4.3

Problem

This is a simple problem and solution about how you can figure out whether an itemRenderer is selected and therefore can display itself accordingly.

Solution

Use a custom itemRenderer where you override the updateDisplayList function: ListBase(owner).isItemSelected(data); The full explanation is below.

Detailed explanation

In this example, the selected item will change its fontSize, color and fontWeight.

package {

    import mx.controls.Label;
    import mx.controls.listClasses.*;

    public class MyLabel extends Label  {

        override protected function updateDisplayList(unscaledWidth:Number,                    
            unscaledHeight:Number):void
        {
            super.updateDisplayList(unscaledWidth, unscaledHeight);
             
            //figure out if this itemRenderer is selected
            if(ListBase(owner).isItemSelected(data))
            {
                setStyle('fontSize',14);
                setStyle('fontWeight', 'bold');
                setStyle('color', 0xDD0000);
           }
         
           //otherwise, return the label to its regular state
           else
           {
                setStyle('fontSize', 10);
                setStyle('fontWeight', 'normal');
                setStyle('color', 0x000000);
            }
        } 
    }
}

I have subclassed a Label because it is pretty lightweight and supports all of the styles that I want to set.  In the custom itemRenderer, I have overridden the updateDisplayList function which gets called whenever a change is made to the List. Since a List recycles its rows, you have to set the styles on the cell that is selected and then set them back to the defaults when it is not selected.
selectedSample.zip
[This includes a sample Application (mxml), the custom itemRenderer and the compiled swf.]
Report abuse

Related recipes