2011-07-18 49 views
0

我的應用程序具有按鈕,用戶按下可將預定義的字符串插入到textarea中。我現在正在動態加載按鈕值,以便用戶可以定義他們自己的按鈕。Flex:將事件分配給動態創建的按鈕

我使用了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

目前還不清楚,如果要添加文本按鈕或不同的文字相同的標籤。無論如何,當你創建按鈕時,你可以添加一個事件列表器。假設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

希望這可以幫助

+0

這是完美的感謝! :) – RapsFan1981

+0

哦,對不起,這是不同的文字。例如Button1作爲標籤「Hello」作爲字符串 – RapsFan1981

+0

請參閱編輯我的更新後的代碼和我的txt文件的結構 – RapsFan1981

相關問題