Adding and Removing Components

One of the most common uses of states is adding and removing components. You can use the <mx:AddChild> tag to add a component or components. Example 12-4 defines a state named newTextInput that adds a text input component instance.

Example 12-4. Basic addition of a component using a state

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">

    <mx:Button id="button" label="Add Text Input"
        click="currentState='newTextInput';" />

    <mx:states>
        <mx:State name="newTextInput">
            <mx:AddChild>
                <mx:TextInput id="textinput" />
            </mx:AddChild>
        </mx:State>
    </mx:states>

</mx:Application>

The default behavior of the <mx:AddChild> tag is to add the component or components to the application container or component for which the state is defined. However, if you want to define an explicit target to the component (or components) you added, use the relativeTo attribute. Example 12-5 adds the new text input as a child of the VBox instance with an id of vbox.

Example 12-5. Adding one component relative to another

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">

    <mx:VBox id="vbox">
         <mx:CheckBox id="checkbox1" label="One" />
         <mx:CheckBox id="checkbox2" label="Two" />
         <mx:Button id="button" label="Add Text Input"
             click="currentState='newTextInput';" />
     </mx:VBox>

    <mx:states>
        <mx:State name="newTextInput">
            <mx:AddChild relativeTo="{vbox}"> <mx:TextInput id="textinput" ...

Get Programming Flex 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.