actionscript-3apache-flexflex4flex4.6

Flex4 List itemRenderer isItemSelected() method


In flex3, List has isItemSelected() method, but I didn't find them in flex4. My scenario is determining whether the current ItemRenderer is selected or not, and then depends on the selected value, do some logic on specific component in the ItemRenderer(suppose ItemRenderer has an Image component and Label component, I only want to do some logic on the Image)


Solution

  • In Flex 4, item renderer functionality can make better use of states. What this means is that they have the default states, which we can use them to implement state-specific logic:

    normal
    hovered
    selected
    up
    

    If you want to do something when the item becomes selected, you could add a listener for the stateChangedComplete event, and implement your logic in that handler (of course, you would have to test if the current statate is 'selected'). The code could look something like this:

    <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"
                    stateChangeComplete="stateChangedHandler()"
                    autoDrawBackground="false">
    
        <fx:Script>
            <![CDATA[
                protected function stateChangedHandler():void
                {
                    if(currentState == "selected")
                    {
                        // implement your logic here
                    }
                }
            ]]>
        </fx:Script>
    
        <!-- Your original MXML code here -->
    
    </s:ItemRenderer>
    

    This would be the way to go, if you need some non-trivial logic done. If, however, you just need to change some attributes on the image, when the item renderer becomes selected, you could just specify a state-specific property/value pair on the element instead, like so (let's assume the images are faded by default, and when the item is selected, you want to fade them in, for the sake of the explanation):

    <s:Image alpha="0.5" alpha.selected="1" />
    

    This way, no listener/handler is required.

    Hope this helps. Have a great day.