tags:

views:

73

answers:

1

Hi,

I wanna add dynamically (at runtime) new states to a container and, to this states, add different elements (like TextInput, Label etc.). This must be done from actionscript, I don't use any mxml file. I can add states and change properties or styles for different elements, but I didn't figured out how to add child elements for different states.

Thank you.

Cristi

A: 

You'll have to manually create an instance of the State class and create overrides for it. Then add the newly created state to the states array of your component.

Here's a small example air application that shows how to do it:

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication 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;
            import mx.states.AddChild;
            import mx.states.AddItems;
            import mx.states.SetProperty;
            import mx.states.State;

            protected function createState(event:MouseEvent):void
            {
                var label:Label = new Label();
                label.text = "World!";

                var addLabel:AddItems = new AddItems();
                addLabel.relativeTo = foo;
                addLabel.position = "after";
                addLabel.items = label;

                var helloWorld:State = new State();
                helloWorld.name = "helloWorld";
                helloWorld.overrides = [addLabel];

                states = [helloWorld];
                currentState = "helloWorld";
            }
        ]]>
    </fx:Script>

    <s:layout>
        <s:VerticalLayout />
    </s:layout>

    <s:Label id="foo" text="Hello" />

    <s:Button label="Create new state" click="createState(event)" />
</s:WindowedApplication>
macke
Thank you for your quick response.
accexpert
This I already figured out But I wanna add to a particular custom state new elements like: TextInput, Label etc. so I can show at runtime different elements for different states created dynamically.
accexpert
The same concept applies, only you use the AddItems or AddChild overrides instead. Use the former for adding children to Spark (Flex 4) containers and the latter for MX (Flex 3) components. I've updated the sample to show how it would work in this application.
macke
Thank you very much. Was very helpfull. Best regards, Cristi
accexpert
Glad to help. Please mark my answer as accepted if it helped you out, thanks!
macke