Monday, June 13, 2011

Using Actionscript in Flex

In the last tutorial we created a simple "Hello world" application using just mxml. Let's add some interactivity today.

We can add interactivity by adding some Actionscript code. But first, let's edit our application's appearance.

We have a text field and a button so far. We will now add an input text field. Then we will add a function, that will change the Label's text value to the input field's value, once the button is pressed. Let's see how it is done.

Firstly, create an input field. An input field is a TextInput object in the spark namespace. We will set its coordinates, width and id. In the end, our code will look like this:

<?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">

<s:Group x="20">
<s:Label text="Type text below to change this text!" x="10" y="10" id="myText" />
<s:TextInput x="10" y="30" width="100" id="myInput" />
<s:Button label="Click me!" x="10" y="55" />
</s:Group>

</s:Application>

Now, let's create this function that will do the text change.

We can't just go around mxml files writing AS3 code wherever we want. This needs to be done in the fx:Script tags. Moreover, the code needs to be included in the <![CDATA[ ]]> container thing.

<fx:Script>
<![CDATA[
// AS3 code here
]]>
</fx:Script>

So let's go ahead and write our function there. It will receive a text value as a parameter and then set it as a text value of the myText Label object.

<fx:Script>
<![CDATA[
public function changeTextTo(val:String):void{
myText.text = val;
}
]]>
</fx:Script>

Now all that is left to do is to apply this function to our button. We simply call it and pass the variable by using the 'click' attribute of our Button.

With that applied, the final code will be:

<?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">

<fx:Script>
<![CDATA[
public function changeTextTo(val:String):void{
myText.text = val;
}
]]>
</fx:Script>

<s:Group x="20">
<s:Label text="Type text below to change this text!" x="10" y="10" id="myText" />
<s:TextInput x="10" y="30" width="100" id="myInput" />
<s:Button label="Click me!" x="10" y="55" click="changeTextTo(myInput.text);" />
</s:Group>

</s:Application>

Try it out:


Thanks for reading!

No comments:

Post a Comment