Flex 4 - 在actionscript中创建状态并在运行时添加元素

时间:2010-09-28 12:49:08

标签: flex

我想动态地(在运行时)将新状态添加到容器中,并且对于此状态,添加不同的元素(如TextInput,Label等)。这必须从actionscript完成,我不使用任何mxml文件。我可以添加状态并更改不同元素的属性或样式,但我没有想出如何为不同的状态添加子元素。

1 个答案:

答案 0 :(得分:4)

您必须手动创建State类的实例并为其创建替代。然后将新创建的状态添加到组件的states数组中。

这是一个小例子航空应用程序,展示了如何做到这一点:

<?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>