2

I have very basic question about Flex SDK, but I didn't find any resources for my problem and honestly don't know if it even possible to do what I want. So here is my question:

I created Flex project with Adobe Flex Builder 4.6. Then I placed the button (let's say it's id is btn1) in main MXML file. I want to create second button dynamically right from the script part of main MXML file. Specifically I want to create it from button click handler of btn1.

Here is my MXML code (it is the only file in project ):

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/mx" 
               minWidth="955" minHeight="600">

    <fx:Script>
        <![CDATA[
            protected function btn1_clickHandler(event:MouseEvent):void
            {
                var btn2:Button = new Button();
                btn2.label = "Hello";
                btn2.x = 50;
                btn2.y = 50;
            }
        ]]>
    </fx:Script>


    <fx:Declarations>
        <!-- Non visual elements -->
    </fx:Declarations>

    <s:Button id="btn1" 
              x="10" y="10" 
              label="Кнопка"
              click="btn1_clickHandler(event)"/>

</s:Application>

But when I click btn1 - nothing happens. It is possible that I don't understand something in flex programming paradigm - please point it out for me.

5
  • addChild() that button, at the very least. Commented Oct 30, 2012 at 11:06
  • 2
    Don't use addChild(). Use addElement(). Commented Oct 30, 2012 at 11:09
  • @Florent oh thank you it works! How can I mark your comment as an answer to my question? Commented Oct 30, 2012 at 11:14
  • @Florent Does Flex use addElement for any of its components, that are contained in spark or mx? I'm unfamiliar with Flex, while I have some experience with AS3. Commented Oct 30, 2012 at 11:23
  • If you decompile your SWF, you will understand how it works internally! Flex converts MXML files to AS3 and then uses addElement() to rebuild the MXML structure. Commented Oct 30, 2012 at 11:30

1 Answer 1

2

You have to add the button to the view using addElement().

var btn2:Button = new Button();
btn2.label = "Hello";
btn2.x = 50;
btn2.y = 50;

addElement(btn2);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.