You typically use MXML to lay out the user interface of your application, and use ActionScript for event handling and runtime control of the application. You can also use ActionScript to create component instances at runtime. For example, you can use MXML to define an empty Accordion container. Then, in ActionScript, add additional panels to the Accordion container in response to user actions.
To create a component instance at runtime, you create it as a child of a parent container by calling the View.createChild() method on the parent container. This method has the following signature:
createChild(classOrSymbol:var, undefined, initProps:Object) : MovieClip;
where:
You must specify the fully qualified class name of the component that you want to create. For example, if your application has an HBox container named myHB, the following code creates a Button control within that container:
myHB.createChild(mx.controls.Button);
If you first import the class that you want to create, you only need to specify the class name, as the following example shows:
import mx.controls.Button; myHB.createChild(Button);
undefined. This argument is optional, and is necessary only as a placeholder if you want to specify the initProps argument.
The initProps argument lets you pass initialization properties to the component you are creating. You can pass to it the same properties that you can set in MXML for the component. For example, to create a Button control with the label New Button and a height and width of 100 pixels, you pass an initProps argument as the following example shows:
import mx.controls.Button; myHB.createChild(Button, undefined,
{label:'New Button', width:100, height:100});
The createChild() method returns a MovieClip object representing the new component. You often assign the return value of the createChild() method to a variable so that you can manipulate the component programmatically. For example, the following code creates a Button control:
import mx.controls.Button; var myNewButton:Button; myNewButton = Button(myHB.createChild(Button));
It is a good practice to cast the return value of the createChild() method to the data type of the new component so that the Flex compiler can perform type-checking on the variable if you use it to manipulate the component. For example, you can use the following code to increase the height and width of the Button control by 100 pixels:
myNewButton.height+=100; myNewButton.width+=100;
You can also use the mx.core.View class's destroyChild() method to delete a control, as the following example shows:
myHB.destroyChild(myNewButton);
For additional methods that you can use with container children, see the View class in Flex ActionScript and MXML API Reference.
Version 1.5
Send me an e-mail when comments are added to this page | Comment Report
Current page: http://livedocs.adobe.com/flex/15/flex_docs_en/00002167.htm