在ActionScript中动态创建Flex组件

时间:2010-06-08 22:56:13

标签: flex flash actionscript-3 actionscript air

是不是有某种方法可以重写下面的代码,这样我就不需要每个可想到的类型都有一个巨大的switch语句?另外,如果我可以用某种方式替换switch语句来动态创建新控件,那么我可以使代码更小,更直接,而不必预测自定义控件类型的可能性。

在:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" 
  layout="vertical">
  <mx:Script>
    <![CDATA[
      import mx.containers.HBox;
      import mx.controls.Button;
      import mx.controls.Label;
      public function CreateControl(event:Event):void {
        var Type:String=Edit.text;
        var NewControl:Object;

        switch (Type) {
          case 'mx.controls::Label':NewControl=new Label();break;
          case 'mx.controls::Button':NewControl=new Button();break;
          case 'mx.containers::HBox':NewControl=new HBox();break;
          ... every other type, including unforeseeable custom types
        }

        this.addChild(NewControl as DisplayObject);
      }
    ]]>
  </mx:Script>
  <mx:Label text="Control Type"/>
  <mx:TextInput id="Edit"/>
  <mx:Button label="Create" click="CreateControl(event);"/>
</mx:WindowedApplication>

在:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" 
  layout="vertical">
  <mx:Script>
    <![CDATA[
      import mx.containers.HBox;
      import mx.controls.Button;
      import mx.controls.Label;
      public function CreateControl(event:Event):void {
        var Type:String=Edit.text;

        var NewControl:Object= *???*(Type);

        this.addChild(NewControl as DisplayObject);
      }
    ]]>
  </mx:Script>
  <mx:Label text="Control Type"/>
  <mx:TextInput id="Edit"/>
  <mx:Button label="Create" click="CreateControl(event);"/>
</mx:WindowedApplication>

1 个答案:

答案 0 :(得分:4)

看一下flash.utils.getDefinitionByName()。

我没有运行此代码,但您应该可以按照

的方式执行某些操作
public function CreateControl(event:Event):void {
    var Type:String=Edit.text;
    var controlClass:Class = getDefinitionByName(Type) as Class;

    var NewControl:Object= new controlClass();

    this.addChild(NewControl as DisplayObject);
}