0
votes

i have this source in flex - easy program which switch between two states..in second state is show myImage component

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/mx" 
               xmlns:components="components.*">

    <fx:Script>
        <![CDATA[
            protected function button1_clickHandler(event:MouseEvent):void
            {
                if (currentState == "state1")
                    currentState = "state2";
                else
                    currentState = "state1";                        
            }
        ]]>
    </fx:Script>

    <s:states>
        <s:State name="state1" />
        <s:State name="state2" />
    </s:states>

    <components:myImage includeIn="state2"/>

    <s:Button label="switch states" click="button1_clickHandler(event)" />
</s:Application>

component myImage is here:

<?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009" 
         xmlns:s="library://ns.adobe.com/flex/spark" 
         xmlns:mx="library://ns.adobe.com/flex/mx" >
    <fx:Script>
        <![CDATA[
            import mx.events.FlexEvent;

            protected function img_creationCompleteHandler(event:FlexEvent):void
            {
                trace("image width " + img.width);
            }
        ]]>
    </fx:Script>
    <mx:Image id="img" source="obr.jpg" creationComplete="img_creationCompleteHandler(event)"/>
</s:Group>

if the same code as myImage.mxml put to main application then trace print correct value..but now when i click to button and switch to state2 then trace print width as 0..why? after which event is image in state2 loaded and i can use image.width property??

thanks for help

2

2 Answers

1
votes

The reason why it doesn't have a width is because your image isn't loaded yet. It still needs to get the image from your server to work. There are two thing you can do. You can embed the image so that on creationComplete the image is already there (to embed, just do @Embed('image.jpg') for the source), or wait for the image to load using the complete event, but then it's not 100% that your container (Image) will resize right away. You can try doing a callLater for your trace. Try debugging and check for contentWidth property on the image, that might be a better property to use since it relates to the image itself, not the container.

0
votes

Try to add itemCreationPolicy="immediate" to the image the following way:

<components:myImage includeIn="state2" itemCreationPolicy="immediate" />