Flex:将事件分配给动态创建的按钮

时间:2011-07-18 23:54:49

标签: flex actionscript text button text-files

我的应用程序具有用户按下以将预定义字符串插入文本区域的按钮。我现在正在动态加载按钮值,以便用户可以定义自己的按钮。

我正在使用buttons.txt,每行包含不同的标签(button1,button2,button3等)。我遍历文本文件并将按钮添加到组中。这一切都有效,但现在很难。如何为这些按钮分配eventlistener,以便它们将文本输出到屏幕?

protected function view1_viewActivateHandler(event:ViewNavigatorEvent):void
        {
            var path:File = File.documentsDirectory.resolvePath("buttons.txt");
            myTextLoader.load(new URLRequest("file://" +path.nativePath));
            myTextLoader.addEventListener(Event.COMPLETE, onLoaded);
            trace(path.nativePath); // Traces correct file path

            mainTextField.addEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATE, resizeTextField);
            if(data!=null){
                mainTextField.text = data.toString();
            }else{
                mainTextField.text = tags;
            }
        }

        protected function onLoaded(e:Event):void {
            var myArrayOfLines:Array = e.target.data.split(/\n/);
            var tempBtn:Button;
            trace(myArrayOfLines[0]);
            for(var i:Number = 0;i < myArrayOfLines.length;i++){
                tempBtn = new Button();
                tempBtn.label = myArrayOfLines[i];
                btnArray.push(tempBtn);
                group.addElement(btnArray[i]);
            }
        }

修改

    protected function onLoaded(e:Event):void {
                var myArrayOfLines:Array = e.target.data.split(/\n/);
                var tempBtn:Button;

                for(var i:Number = 0;i < myArrayOfLines.length;i++){
                    var j:Number = i+1;
                    tempBtn = new Button();
                    tempBtn.id = "btn" + i;
                    tempBtn.addEventListener(MouseEvent.CLICK, function(evt:MouseEvent):void{
                        var index:uint = parseInt(evt.currentTarget.id.replace("btn", ""));
                                    //TextArea code will go here

trace(text); // Traces null
                    });
                    tempBtn.label = myArrayOfLines[i];
                    btnArray.push(tempBtn);
                    group.addElement(btnArray[i]);
                }
            }


buttons.txt
     button1_label
    "Hello"
    button2_label
    "Goodbye"
    button3_label
    "Come again"

1 个答案:

答案 0 :(得分:1)

目前尚不清楚您要添加的文本是否与按钮的标签相同或是否为其他文本。无论如何,当您创建按钮时,您可以添加事件列表器。假设txtArr是一个包含要添加的字符串的简单数组

for(var i:Number = 0;i < myArrayOfLines.length;i++){
    tempBtn = new Button();
    tempBtn.id = "btn" + i;
    tempBtn.addEventListener(MouseEvent.CLICK, function(evt:MouseEvent):void{
        var index = parseInt(evt.currentTarget.id.replace("btn", ""));
        var text:String = textArr[i] as String;
    });
    tempBtn.label = myArrayOfLines[i];
    btnArray.push(tempBtn);
    group.addElement(btnArray[i]);
}

简单来说,只需使用id字段存储按钮的当前id,然后在触发事件时从id中获取索引号并从数组中读取文本。然后你只需要将文本字符串添加到textarea

希望这有帮助