<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal" backgroundColor="#FFFFFF" viewSourceURL="srcview/index.html"> <mx:Script> <![CDATA[ import mx.controls.List; public function createNewList(event:MouseEvent):void{ /* Create a new list control */ var tempListControl:List = new List(); /* Add the new list control to the app */listBoxes.addChild(tempListControl); /* Set the data provider & label field */ tempListControl.labelField="@label"; tempListControl.dataProvider = mydata; } ]]> </mx:Script> <mx:VBox horizontalAlign="center"> <mx:HBox> <mx:Button id="newList" label="Add a new List Control" click="createNewList(event)"/> </mx:HBox> <mx:HDividedBox id="listBoxes" width="100%" height="200"/> </mx:VBox> <mx:XMLList id="mydata" xmlns=""> <data label="list item 1"/> <data label="list item 2"/> <data label="list item 3"/> <data label="list item 4"/> </mx:XMLList> </mx:Application>
Explanation
This Flex App is primarily ActionScript Code. To start with, there is a MXML tag which does nothing more than call the createNewList method. This is accomplished by using the CLICK event which is specified by setting the attribute of the <mx:Button> tag. On click of this button, the createNewLIst method is called. This method is where all the work is done. We will break this method down into its basic parts in a moment, but lets first analyze the other mxml tags.
The tags other than the <mx:Button> tag are only responsible for layout formatting and the data provider. These layout containers serve to create a vertical parent box (<mx:Box>) which has center alignment (and contains ALL other UI objects), a horizontal box (<mx:Box>) which holds a place for our button so that it appears on a line by itself, and finally a horizontal <mx:HDividedBox> which is where the new List Controls are added.
The data provider exists to have some data populated in our dynamically created list controls. We don't get too fancy in this example, so, all of our lists will have the same data and therefore have the same items. If you adapt this technique to your own code, you'll be populating the lists with your own data.
So, that brings up to the createNewList method. The first directive/definition in this method is the following:
/* Create a new list control */
var tempListControl:List = new List();
/* Add the new list control to the app */
listBoxes.addChild(tempListControl);
/* Set the data provider & label field */
tempListControl.labelField="@label";
tempListControl.dataProvider = mydata;
These two lines are the last in our method. The first line tells the List Control where is should retrieve the data for the list. In this case, our XML has an attribute called label which contains the this data. The second line assigns our XMLList to the data provider of the List Control.
Here is the final application:
Well, that is it. Code is pretty straight forward. Enjoy!
Related Links: