Wednesday, January 19, 2011

Learn About Flex "Hero" and Flash Builder "Burrito" Beta Preview

Lynda.com has just released a training course entitled Flex "Hero" and Flash Builder "Burrito" Beta Preview. This 2-hour course by James Talbot gives you an in-depth tour of the first version of this Flash-based development platform to be targeted at mobile development. You'll look at the basics of creating and testing an app and get to know the new features in Flash Builder for development and debugging on Android, and the new code generation features, such as templates and Quick Assist, which will help increase productivity.

For $25, you get 1-month unlimited access to not just this training course, but all of Lynda.com's 50,000+ video tutorials. No long-term commitment required. You can cancel your membership at any time. Visitors of this site can avail of a 7-day FREE trial to Lynda's online training library that contains thousands of videos.


Title: Flex "Hero" and Flash Builder "Burrito" Beta Preview
Instructor: James Talbot
Topics:
  1. Preparing for Mobile Development
    • Downloading and configuring the software on a PC
    • Installing and configuring the software on a Mac
    • Installing AIR on a device
    • Using the Android emulator
  2. Building a Mobile Application
    • Creating and testing a mobile project
    • Testing the application on a device and on the Android emulator
    • Understanding mobile application views
    • Accessing remote data from the mobile application
    • Switching views in the mobile application
    • Using a mobile icon item renderer
    • Creating a detail view
  3. Productivity Enhancements in Flash Builder "Burrito"
    • Using code templates
    • Metadata code completion
    • Using the Override/Implement Methods dialog
    • Using Quick Assist
    • Using the "generate from usage" feature
    • Using round-trip graphics editing with Flash Catalyst


Here are a few sample videos from the training title:

Welcome



The Android Emulator



Creating the Detail View



Monday, January 17, 2011

AS3 - Play Sound from Library

Exercise File:
claps.wmv

*Sound loop created by Brad Sucks.

In this tutorial, we're going to learn how to use ActionScript 3 in order to control sound. This lesson comes with an audio file, which you can download from the link above. The file is named claps.wav, which is a short 4-second sound file.

We will be importing the sound file into the Flash document's library. But instead of adding the sound to the timeline, we'll be accessing it using ActionScript code. We'll also learn how to make the sound loop using the AS3 Event.SOUND_COMPLETE event.

NOTE: WAV files are ideal for sound loops, because they can be made to loop seamlessly. MP3 files, on the other hand, are NOT good for looping. MP3 files are not ideal for sound loops because MP3 audio files have a short silent gap at the end (due to the compression algorithm being used). So if you loop an MP3 file, you will have these short silent gaps in between each loop that make the loop sound as if it's skipping.

Step 1

Let's start by creating a new Flash ActionScript 3 Document.

Step 2

On the stage, let's draw 2 buttons - a play button and a stop button. We'll be using these buttons to start and stop our sound. Let's give the the play button an instance name of play_btn and stop_btn for the stop button.

Step 3

Once you have the buttons, let's go ahead and import the claps.wmv audio file into the Flash document's library. From the main menu, choose File > Import > Import to Library. Navigate to where the claps.wmv file is in your computer and import the file. When importing is done, you should see the audio file in the Flash document's library.

Step 4

At this point, let's set up the sound file in our library so that we will be able to access it using ActionScript. To do that, right-click on the sound file in the library and choose Properties.
 
When the Sound Properties dialog box comes up, go to the part that says Linkage. If you don't see this area, click on the Advanced button at the bottom of the dialog box. Once you see the Linkage options, make sure that the following are checked:
  • Export for ActionScript
  • Export in frame 1
This will ensure that our audio file will be exported for ActionScript so that we can control it using code. Export in frame 1 means that the audio file will be exported to frame 1. That way, the sound file will be available to us from the very beginning of the Flash movie. But this does not mean that the sound will play immediately. It simply means that it's available to us starting from the very first frame.

Step 5

After we've checked those options, you'll see a couple of input fields become accessible right below the check boxes. Go to the Class input field and change the name to Claps. This allows us to create a class from our audio file. We will use this class in order to create an instance of our claps.wmv sound file, so make sure you remember this name (Claps) because we will use it later on.

NOTE: This class name is author defined. You can give it any name you want as long as it does not conflict with other class names in your project. The class name is case-sensitive.

Step 6

Double-check to see if you've set everything up properly and then click on OK. You will then get a message that says: A definition for this class could not be found in the classpath, so one will be automatically generated in the SWF file upon export. Click OK so that the Claps class will be generated once you export your SWF.

Now that the sound file in our library is properly set up for use with ActionScript, let's go ahead and write some code.

Step 7

Create a new layer for the Actions, select the first keyframe of that layer, and launch the Actions Panel.

Step 8

Let's go ahead and create an instance of the claps.wmv sound. Remember that the class name we specified is Claps. So type the following line in the script pane:
var clapsSound:Claps = new Claps();
Here, we've created a new instance of the Claps class, which is the class name that we assigned to the claps.wmv file in our library. We've named this instance clapsSound. To hear the claps.wmv audio file, we simply have to play the clapsSound instance. You can do this using the play() method. But before we do that, let's add event listeners to the buttons that we made earlier.

Step 9

So let's go ahead and create mouse click event listeners for our play (play_btn) and stop (stop_btn) buttons:
var clapsSound:Claps = new Claps();

play_btn.addEventListener(MouseEvent.CLICK, playSound);
stop_btn.addEventListener(MouseEvent.CLICK, stopSound)

function playSound(e:MouseEvent):void
{

}

function stopSound(e:MouseEvent):void
{

}
Here, we've created 2 event listener functions - playSound for playing the sound, and stopSound for stopping the sound.

Step 10

Inside the playSound event listener function, let's use the play() method of the Sound class in order to instruct the sound to start playing once the button is clicked:
function playSound(e:MouseEvent):void
{
     clapsSound.play();
}
So now, if you test the movie, clicking on the play button will start playing the sound. We'll learn how to stop the sound in the next step.

Step 11

For stopping the sound, we'll need to create another object of a different type. Simply adding clapsSound.stop() will NOT work, because the stop() method for sounds belongs so another class - the SoundChannel class. And after we've created this SoundChannel object, we'll need to assign clapsSound.play() to it. This will allow us to stop the sound using the stop() method of the SoundChannel class:
var clapsSound:Claps = new Claps();
var clapsChannel:SoundChannel = new SoundChannel(); 
// our SoundChannel object

play_btn.addEventListener(MouseEvent.CLICK, playSound);
stop_btn.addEventListener(MouseEvent.CLICK, stopSound)

function playSound(e:MouseEvent):void
{
     clapsChannel = clapsSound.play();
     // assign the play() method call to the
     // SoundChannel object
}

function stopSound(e:MouseEvent):void
{
     clapsChannel.stop(); 
     // use the stop() method of the
     // SoundChannel class to stop the sound
}
So if we test the movie at this point, we can now successfully play and stop our library sound.

In the next part of this article, we'll learn how to make the sound clip loop.

Making a Sound Clip Loop in AS3

If we want to make the sound loop, we'll need to find a way to be able to tell it to play again once the sound has completed the playback (i.e. when it reaches the end). We can use the SoundChannel class to achieve this. The SoundChannel class has an event associated with it called Event.SOUND_COMPLETE. This event gets dispatched whenever a sound that's playing in a SoundChannel has completed playback. So we can create an event listener for this event, and then tell the sound to play again once this event gets dispatched (i.e. tell the sound to repeat when it reaches the end).

Let's go ahead and create the event listener function first. Let's name it loopSound. Inside this listener function, we'll instruct the sound to play again. So we'll need to add another call to the sound's play() method statement inside this new function:
function playSound(e:MouseEvent):void
{
     clapsChannel = clapsSound.play();
}

function stopSound(e:MouseEvent):void
{
     clapsChannel.stop();
}

function loopSound(e:Event):void
{
     clapsChannel = clapsSound.play();
     trace("The sound has reached the end");
}
I've added in a trace statement so that we will get a message from the Output window once the sound has reached the end.

So, now that we've created this listener function, let's go ahead and register it to our SoundChannel object (clapsChannel).

If you're registering an event listener function to the Event.SOUND_COMPLETE event of the SoundChannel class, you must add the event listener only AFTER the sound has been assigned to the SoundChannel (i.e. it must be added after the SoundChannel = Sound.play(); statement). In our example, the first time the sound plays will be when we click on the play button. So we must add the Event.SOUND_COMPLETE listener after the clapsSound.play() statement inside the playSound() function:
function playSound(e:MouseEvent):void
{
     clapsChannel = clapsSound.play();
     clapsChannel.addEventListener(Event.SOUND_COMPLETE, loopSound);
}
So now, go ahead and test your movie. When you click on the play button, the sound will start playing. And then when it reaches the end, you will see a message from the Output window (from our trace statement), and the sound will immediately play again.
After you've tested the movie and played the sound, you will notice that the sound will only repeat ONCE. After the second time it plays, it will no longer repeat itself. So here, we see that the Event.SOUND_COMPLETE listener will only listen out for the event ONCE. It's not going to keep watching out for Event.SOUND_COMPLETE indefinitely.

But what if we want it to listen out for Event.SOUND_COMPLETE indefinitely so that we can make our sound loop indefinitely as well?
In order to do that, we'll need to add the event listener AGAIN after it begins playing the succeeding time. So we'll also need to add the Event.SOUND_COMPLETE listener inside the loopSound() function right after the sound plays:
function loopSound(e:Event):void
{
     clapsChannel = clapsSound.play();
     clapsChannel.addEventListener(Event.SOUND_COMPLETE, loopSound);
}
So now, we have the add event listener statement for the Event.SOUND_COMPLETE listener in both the playSound() and loopSound() functions. That way, each time the sound plays, Flash will watch out for when the sound completes the playback and will play the sound again. This results in a sound file that loops indefinitely.

NOTE: If you want more than one sound clip to loop simultaneously using this method, then you'll have to create one SoundChannel for each sound.

And that concludes this tutorial on how to play sound from the library using AS3 and AS3 sound looping.

Wednesday, January 12, 2011

AS3 Sound

Exercise Files:
Sound.fla
CheerfulSong.mp3

In this lesson, we're going to learn how to control sound in Flash using ActionScript 3. We're going to learn:
  • how to load an external sound file into a Flash movie
  • how to play and stop the sound
  • how to detect when the sound clip has reached the end

Exercise files accompany this article - we have a Flash document named Sound.fla and an mp3 document named CheerfulSong.mp3. Please make sure to save them both inside the same folder. In the first part of this tutorial, we'll learn how to load CheerfulSong.mp3 into our Flash movie using ActionScript. Instead of importing CheerfulSong.mp3 into Sound.fla's library, both files will remain separate from each other, but we will use ActionScript so that we will be able to play the sound from within the Flash movie.

Let's begin.

Loading and Controlling an External Sound File

How do you control sound using ActionScript 3?
To control sound in your Flash movie using code, create a Sound object using the the AS3 Sound class to control the sound .

A Sound object can be used to do the ff:
  • load an external sound file into a Flash movie
  • start the playback of that loaded sound file

NOTE: You can NOT use a Sound object to stop playing sound. The Sound class does not have a method for that. If you want to stop a sound clip's playback, you'll have to use a different class - the AS3 SoundChannel class - which we will talk about later. 

STEP 1

Open the Sound.fla file. You'll see that there are two buttons on the stage - play_btn and stop_btn. But let's ignore those buttons for now. First, let's write some code that will load and play the sound right away. Select frame 1 of the Actions layer, then go to the Actions Panel and type in the following lines:
var mySound:Sound = new Sound();
var myURL:URLRequest = new URLRequest("CheerfulSong.mp3");
The first line (var mySound:Sound = new Sound();) creates an instance of the Sound class. I've named it mySound. We will use this to load and play the external sound file named CheerfulSong.mp3.

The second line (var myURL:URLRequest = new URLRequest("CheerfulSong.mp3");) creates a URLRequest object. This is used to specify the path to the external file that we want to load.

STEP 2

So now that we've created those two objects, we can now load the external sound file. Use the load() method of the Sound class and pass to it the URLRequest object:

Sound.load(URLRequest);

So in our example, we would write:

mySound.load(myURL);

This instructs our mySound object to load the file specified in myURL (which is CheerfulSong.mp3). So go back to the code and add the following line highlighted in bold:
var mySound:Sound = new Sound();
var myURL:URLRequest = new URLRequest("CheerfulSong.mp3");

mySound.load(myURL);

NOTE: When using the load() method of the Sound class, the external sound file must be in the mp3 format. And if you want to load more than one sound file, then create another Sound object for each succeeding sound file that you'd like to load, even if you're reloading the same sound file.

STEP 3

If you test the movie at this point, you won't hear the sound just yet. That's because we just told Flash to load the sound. We haven't given the instruction to start playing the sound yet. To make the sound start playing, we use the play() method of the Sound class:
var mySound:Sound = new Sound();
var myURL:URLRequest = new URLRequest("CheerfulSong.mp3");

mySound.load(myURL);
mySound.play();
So if you test the movie now, you should hear the sound playing.

The play() method of the Sound class has 2 optional parameters:
  1. startTime - this lets you specify the point (in milliseconds) where the sound playback should start
  2. loops - this lets you specify how many times the sound should repeat playback
For example, lets pass values to these 2 parameters like so:

mySound.play(25000, 2);

The first value refers to the startTime parameter. Here, we've specified a value of 25000 milliseconds (or 25 seconds). This means that when the sound begins playing, it will start playing at the sound's 25-second mark, instead of starting at the beginning. So it will skip the first 24 seconds of the song when the playback starts.

The second value refers to the loops parameter. We've specified a value of 2. This means that the sound will play 2 times. When it plays the first time and then reaches the end, it will loop back to the startTime and play one more time.

Test the movie in order to verify, and then change the play statement back to mySound.play(); (without any parameters), and let's continue.

STEP 4

If we want the sound to play only after the play button (named play_btn) has been clicked, then we'll have to create a mouse click event listener for the play button, and we'll transfer the play sound statement inside that event listener:
var mySound:Sound = new Sound();
var myURL:URLRequest = new URLRequest("CheerfulSong.mp3");

mySound.load(myURL);
// Make sure that you remove the play sound statement
// that was here, and transfer it into the mouse click
// event listener function

play_btn.addEventListener(MouseEvent.CLICK, playSound);

function playSound(e:MouseEvent):void
{
     mySound.play();
}
Here, we've created a mouse click event listener function named playSound, and we've transferred the mySound.play() statement into that event listener function. So now, when we test the movie, the sound is only going to play when the play button is clicked.

STEP 5

So now that we can play the sound, how do we stop it?
You can NOT stop the sound using the Sound class (e.g. Sound.stop() will not work). Another class is used for that - the SoundChannel class - which has a stop() method that will let you stop a sound's playback.

Let's go ahead and create an instance of the SoundChannel class. I'm going to name it mySoundChannel.
var mySound:Sound = new Sound();
var myURL:URLRequest = new URLRequest("CheerfulSong.mp3");
var mySoundChannel:SoundChannel = new SoundChannel();

mySound.load(myURL);
We now have a SoundChannel object named mySoundChannel.

STEP 6

Think of the SoundChannel as the object that houses or contains your sound. In order to place a sound inside a SoundChannel, you assign the play sound statement to a SoundChannel like so:

SoundChannel = Sound.play();

So in our example, we would write:

mySoundChannel = mySound.play();

This assigns mySound.play() to mySoundChannel, so that the sound is going to play inside mySoundChannel. Let's go ahead and assign mySound.play() to mySoundChannel in our code:
var mySound:Sound = new Sound();
var myURL:URLRequest = new URLRequest("CheerfulSong.mp3");
var mySoundChannel:SoundChannel = new SoundChannel();

mySound.load(myURL);

play_btn.addEventListener(MouseEvent.CLICK, playSound);

function playSound(e:MouseEvent):void
{
     mySoundChannel = mySound.play();
}

STEP 7

So we've now assigned our sound to a channel. In order to stop the sound, then we'll have to stop the SoundChannel that contains the sound. We will use the stop() method of the SoundChannel class like so:

mySoundChannel.stop();

This will stop whatever sound that is playing inside the mySoundChannel object.

Let's put this stop statement inside a mouse click event handler for the stop button (stop_btn) so that our sound will stop playing when the user clicks on the stop button:
play_btn.addEventListener(MouseEvent.CLICK, playSound);
stop_btn.addEventListener(MouseEvent.CLICK, stopSound);

function playSound(e:MouseEvent):void
{
     mySoundChannel = mySound.play();
}

function stopSound(e:MouseEvent):void
{
     mySoundChannel.stop();
}
Here, we've created a mouse click event listener function named stopSound() for the stop button. This event listener function contains the mySoundChannel.stop(); statement. So now, the user can click on the stop button in order to stop the sound's playback.

NOTE: If you want to be able to play multiple sounds simultaneously and still be able to individually stop each sound, then you will need to create one SoundChannel for each sound.

And that concludes the first part of this tutorial. But don't close your Sound.fla document just yet. In the next part, we'll learn how to write some code that will enable Flash to detect when the sound has reached the end. This is useful if you want your Flash movie to do something once a sound clip has completed playback.

Detecting when a Sound has Reached the End

In some cases, you might want to enable Flash to detect when a sound clip has reached the end. Let's say, for example, you have a song that's playing in the background, and you'd like Flash to display an image or a message only when the song has completed playing. To be able to detect when a sound file has reached the end, you can use the Event.SOUND_COMPLETE event of the SoundChannel class. This event gets dispatched once a sound file completes playback.

STEP 1

Let's go ahead and add an Event.SOUND_COMPLETE listener to our code. I'm first going to create the event listener function, which I will name endOfSound.
function playSound(e:MouseEvent):void
{
     mySoundChannel = mySound.play();
}

function stopSound(e:MouseEvent):void
{
     mySoundChannel.stop();
}

function endOfSound(e:Event):void
{
     trace("Sound playback is complete.")
}
Here, we have an event listener function named endOfSound. When this function gets called, it's going to trace a message to the Output window.

STEP 2

Now that we have this event listener function, we then need to add the event listener to our SoundChannel object. When you're adding an Event.SOUND_COMPLETE listener, the event listener must only be added AFTER the line where the play sound statement has been assigned to the SoundChannel (i.e. after the SoundChannel = Sound.play() statement). In our example, this line would be:

mySoundChannel = mySound.play();

And in our code, this line can be found inside the playSound event listener function. So we must add the event listener for Event.SOUND_COMPLETE right AFTER that line:
function playSound(e:MouseEvent):void
{
     mySoundChannel = mySound.play();
     mySoundChannel.addEventListener(Event.SOUND_COMPLETE, endOfSound);
}

function stopSound(e:MouseEvent):void
{
     mySoundChannel.stop();
}

function endOfSound(e:Event):void
{
     trace("Sound playback is complete.")
}
Now that the event listener has been added, Flash can now detect when the sound has reached the end. If you test the movie now and play the song, the trace statement will output the message once the song reaches the end. So whatever other instructions you'd like to tell Flash to do once the song has reached the end (e.g. play another song, stop the animation, go to the next frame, display an image) should be placed inside the Event.SOUND_COMPLETE event listener function.

Lastly, let's learn how to stop playing multiple sound clips all at once.

Stopping All Sounds at Once

In our example, we're only playing one sound file. But what if you have multiple sound clips playing all at the same time and you'd like to stop all of them at once? You can do that by using the stopAll() method of the SoundMixer class. In the example below, we have some code that stops all the sound clips that are currently playing, when a button is clicked:
// Assume that stopAll_btn is a button 
// that already exists on the stage
stopAll_btn.addEventListener(MouseEvent.CLICK, beQuiet);

function beQuiet(e:MouseEvent):void
{
     SoundMixer.stopAll();
}
Here, we've created a mouse click event handler that will enable the user to stop all sound clips that are currently playing by clicking on the button.

And those are the basics of how you can use the AS3 Sound class and the AS3 SoundChannel class in order to work with sound in Flash. And with that, this tutorial is now concluded.

Sunday, January 9, 2011

AS3 TextFormat

In this lesson, we're going to learn how to format the text inside a text field. In order to do that, we are going to learn how to use the ActionScript 3 TextFormat class. This AS3 TextFormat class can be used to apply text formatting properties - such as the font face, font color and the font size - to the contents of a text field.

Let's begin.

Create a new Flash ActionScript 3 document. Then let's go to the Actions Panel and let's start writing some code. Let's start by creating a new AS3 dynamic text field:
var myTextField:TextField = new TextField();

addChild(myTextField);

myTextField.border = true;
myTextField.x = 50;
myTextField.y = 25;
myTextField.autoSize = TextFieldAutoSize.LEFT; 
myTextField.text = "Formatting Text in ActionScript 3";
Here, we've created a new text field named myTextField. If you test the movie, the text is just going to have the default text formatting properties applied.

If you want to format the text - increase / decrease the size, change the font, etc..., then you can use the AS3 TextFormat class. A TextFormat object will hold the text formatting properties, which you can then apply to a TextField object. Some properties from the TextFormat class are:

  • font - to specify the font to be used
  • size - to specify the font size in pixels
  • color - to specify the font color
  • leftMargin - to specify the left margin in pixels
  • rightMargin - to specify the right margin in pixels

Let's go ahead and create a new instance of the TextFormat class. I'm going to name it myTextFormat:
var myTextField:TextField = new TextField();
var myTextFormat:TextFormat = new TextFormat();

addChild(myTextField);

myTextField.border = true;
myTextField.x = 50;
myTextField.y = 25;
myTextField.autoSize = TextFieldAutoSize.LEFT; 
myTextField.text = "Formatting Text in ActionScript 3";
Now that we have a new TextFormat object, let's go ahead and set some of the formatting properties:
var myTextField:TextField = new TextField();
var myTextFormat:TextFormat = new TextFormat();

addChild(myTextField);

myTextFormat.font = "Arial";
myTextFormat.size = 15;
myTextFormat.color = 0x0000FF;
myTextFormat.leftMargin = 30;

myTextField.border = true;
myTextField.x = 50;
myTextField.y = 25;
myTextField.autoSize = TextFieldAutoSize.LEFT; 
myTextField.text = "Formatting Text in ActionScript 3";
Here, we've set new values for the font, size, color and leftMargin. But if we test the movie, we won't see any of the new text formatting properties applied just yet. That's because we have yet to apply the formatting properties to the actual text field. Just because we've created the text format object, that does not mean that the text formatting properties will automatically apply to all the text fields in our Flash movie.

One way of assigning a TextFormat object to a TextField object would be by using the setTextFormat() method of the TextField class. This is how you would use it:

textFieldObject.setTextFormat(textFormatObject);

Here, you see that the TextFormat object is passed to the setTextFormat() method. So in our example, we would write:

myTextField.setTextFormat(myTextFormat);

Also, you should know that this line should always come AFTER the text assignment statement (textField.text = "text"). Otherwise, the formatting will not apply. So let's go ahead and add the setTextFormat() statement, making sure that it comes after the text assignment statement:
var myTextField:TextField = new TextField();
var myTextFormat:TextFormat = new TextFormat();

addChild(myTextField);

myTextFormat.font = "Arial";
myTextFormat.size = 15;
myTextFormat.color = 0x0000FF;
myTextFormat.leftMargin = 30;

myTextField.border = true;
myTextField.x = 50;
myTextField.y = 25;
myTextField.autoSize = TextFieldAutoSize.LEFT; 
myTextField.text = "Formatting Text in ActionScript 3";
myTextField.setTextFormat(myTextFormat);
So if you test the movie now, you should see the text formatting properties applied to the text in our text field.

Formatting Input Text Fields

Formatting an input text field would be pretty much the same as the method we just demonstrated above. However, if our input text field is initially empty, then we can NOT use the setTextFormat() method in order to assign the text formatting to the text field. We can not use the setTextFormat() method because if you recall, the setTextFormat() statement must come AFTER the text assignment statement. So if we don't have a text assignment statement, then there would be no appropriate place to write the setTextFormat() statement. So if that is the case, we can use the defaultTextFormat property of the TextField class instead:

textFieldObject.defaultTextFormat = textFormatObject;

Here, the TextFormat object is assigned to the defaultTextFormat property. So in our example, if we use an input text field that is initially empty instead, we would write:

myTextField.defaultTextFormat = myTextFormat;

As was mentioned previously, this line does NOT need to come after any text assignment statement.

Here's a version of our sample code that uses an input text field instead:
var myTextField:TextField = new TextField();
var myTextFormat:TextFormat = new TextFormat();

addChild(myTextField);

myTextFormat.font = "Arial";
myTextFormat.size = 15;
myTextFormat.color = 0x0000FF;
myTextFormat.leftMargin = 30;

myTextField.type = "input";
myTextField.border = true;
myTextField.x = 50;
myTextField.y = 25;
myTextField.autoSize = TextFieldAutoSize.LEFT; 
myTextField.defaultTextFormat = myTextFormat;

And here's a recap of the difference between setTextFormat() and defaultTextFormat:

setTextFormat()
This is a METHOD of the TextField class.
Use the setTextFormat() method to apply formatting AFTER text is added to a text field.

defaultTextFormat
This is a PROPERTY of the TextField class.
Use the defaultTextFormat property to apply formatting BEFORE text is added to a text field.

And that is how you use the AS3 TextFormat class.

Working with AS3 Input Text Fields

You can add input text fields to your Flash movie in order to allow text-based interaction from your users. An input text field is one that accepts information from the users of your Flash movie. The user simply needs to select the text field and type inside it in order to place information. This is in contrast to a dynamic text field which will only display information, and will not allow the user to alter that information. An input text field can be created using the TextField class as well. You will simply need to set the type to "input". In this article, we're going to learn how to work with input text fields in ActionScript 3. We'll learn how to create them using code, how to set some of the properties, how to set the focus to an input text field, and how to set restrictions to which characters a user can type in them.

Let's begin.

Open a new Flash ActionScript 3 document. Select the first frame and then launch the Actions Panel. In the Script Pane, type in the following code:
var inputField:TextField = new TextField();

addChild(inputField);

inputField.border = true;
inputField.width = 200;
inputField.height = 150;
inputField.x = 75;
inputField.y = 50;
Here, we've created a new instance of the AS3 TextField class, and we've given it an instance name of inputField. We've set some of the text field's properties as well, such as the width, height, border, etc... By default, an instance of the TextField class is of the dynamic type. So if you test the movie now, you won't be able to type inside it. In order to make this instance an AS3 input text field, use the type property of the TextField class, and give it a value of "input" (the value must be specified as a string, i.e it should be in quotation marks).
var inputField:TextField = new TextField();

addChild(inputField);

inputField.border = true;
inputField.width = 200;
inputField.height = 150;
inputField.x = 75;
inputField.y = 50;
inputField.type = "input";
So now that we've set the type to "input", let's go ahead and test the movie. Then click inside the text field and start typing. You should see that the text field will accept your input.

NOTE: After the test movie launches, go to the Control menu and make sure that Disable Keyboard Shortcuts is checked. This is not really a requirement, but whenever you'd like to test the text fields inside your Flash movie, there are some cases where enabled keyboard shortcuts will interfere with your keystrokes. So it's a good idea to disable keyboard shortcuts when you're testing the ActionScript enabled text fields in your Flash movie.

Continue typing inside the input text field and then try pressing the enter or return key on your keyboard in order to move down to the next line. If you find that you are unable to move down to the next line, then you can set the multiline property of the text field to true. If it is set to false, then the text inside your text field will remain in one line regardless of the text field's height and regardless of how many times you press enter or return.
var inputField:TextField = new TextField();

addChild(inputField);

inputField.border = true;
inputField.width = 200;
inputField.height = 150;
inputField.x = 75;
inputField.y = 50;
inputField.type = "input";
inputField.multiline = true;
Now, if you test the movie again, you should see that hitting the enter or return key on your keyboard will let you move down to the next line within your text field.

Moving the Focus to an AS3 Input TextField

You might have noticed that every time you test the movie, you will need to click inside the text field first in order to be able to type inside it. This happens because the focus must be on the input text field first, before it accepts user input. Focus refers to the object on the stage that is currently active. The focus usually moves to a certain object when you mouse over or click on it. So the focus will not automatically go to the input text field just because it's on the stage. If you'd like the focus to move to the input text field right away, then can use the focus property of the stage and set it to the input text field like so:
var inputField:TextField = new TextField();

addChild(inputField);

inputField.border = true;
inputField.width = 200;
inputField.height = 150;
inputField.x = 75;
inputField.y = 50;
inputField.type = "input";
inputField.multiline = true;

stage.focus = inputField;
So now when you test the movie, the focus will quickly move to the input text field, enabling you to type inside it immediately, without having to click inside it first.

REMINDER: Make sure that keyboard shortcuts are disabled.

NOTE: In some cases, even if you have keyboard shortcuts disabled, testing input text fields within the Flash test movie environment can still get buggy. Personally, what I do is I make sure that the Flash movie is saved, then I test the movie in order to generate a SWF file in the same folder where the FLA file is saved. Then I would close the test movie, and then go to the folder that contains the SWF file. I would then open that SWF file and test my input text field(s) there.

Restricting Character Input in AS3

In some cases, you might want to make sure that there are some restrictions as to which characters as well as the number of characters that a user can type inside an input text field. For example, you can create an input text field that will only accept numerical characters, and will only allow a maximum of 5 characters to be type inside it. If you want to limit the number of characters that a user can type inside a given input text field, then you can use the maxChars property of the TextField class. For example:
inputField.maxChars = 10;
This will limit the number of allowable characters that the user can type inside the input text field to a maximum of 10 characters.

NOTE: In the multiline input text field in our example, each time you hit enter or return on the keyboard while the text field is in focus will count as one character subtracted from the character limit. So with a maxChars value of 10, if you hit enter or return in the multiline input text field 2 times before you type in the other characters, then you'll only be able to type in only 8 more.

If you want to put restrictions as to which characters a user can type inside an input text field, then you can use the restrict property of the TextField class. Here's an example:
inputField.restrict = "abcd";
In this example, only the lower case characters a, b, c, and d are ALLOWED. Any other character will not appear in the input text field if the user tries to type them in.

If you want to allow the uppercase characters A, B, C and D, then you'll need to add them to the set like so:
inputField.restrict = "ABCDabcd";
There is no need to add a space between the uppercase letters and the lowercase letters. If you add in a space anywhere in this set of characters, Flash is going to think that you want to allow spaces to be typed inside the input text field. But if you actually want spaces to be allowed, then you can add a space anywhere within the set of characters.

You can also specify a range of characters like so:
inputField.restrict = "A-Z";
In this example, all uppercase character from A to Z are allowed.

In this other example, uppercase A to Z, lowercase a to z, and numerical characters 0 to 9 are allowed:
inputField.restrict = "A-Za-z0-9";

What if I would like to specify characters that should NOT be allowed?
If you want to specify characters that should NOT be allowed, then you start off with a caret (^). For example:
inputField.restrict = "^abcd";
This allows all other characters except for lowercase a, b, c, and d.

In this example, all characters are allowed except for lowercase a to z:
inputField.restrict = "^a-z";

In this example, all characters are allowed except for lowercase a to f, uppercase A to F and numerical characters 3 to 7:
inputField.restrict = "^a-fA-F3-7";
And those are some of the basics on how you can work with AS3 input text fields.

AS3 TextFields - The Basics

In this lesson, we are going to learn the basics of working with the ActionScript 3 TextField class. We'll learn how to create text fields using code, and how to control some of its properties - x and y for positioning the text field, width and height for controlling its size, etc... We'll also learn how to write text inside a text field and how to append or add more text to it using code.

Let's begin.

In order to create an AS3 TextField object using code, instantiate a new instance of the TextField class like so:
var instanceName:TextField = new TextField();

Let's create an example. Open Flash and create a new ActionScript 3 document. Make sure that the first frame on your timeline is selected. Then in the Script Pane of the Actions Panel, type in the following code:
var myTextField:TextField = new TextField();
This creates a new instance of the AS3 TextField class. We've given this new instance the name myTextField. When you test the movie at this point, you won't see anything on the stage. Yes, you've created a new instance of the TextField class, but you still haven't added it to the display list. Use the addChild() method in order to add the text field to the display list:
var myTextField:TextField = new TextField();

addChild(myTextField);
Now at this point, when you test the movie, you still will NOT see the text field. But it's there. The reason why you still don't see it is because it's empty and has no borders. So let's go ahead and use some properties of the TextField class in order to put some text inside our text field and give it a border. We'll be using the following properties:

  • text - assigns and retrieves text inside a text field
  • border - adds or removes a text field's border

var myTextField:TextField = new TextField();

addChild(myTextField);

myTextField.text = "Creating ActionScript 3 TextFields.";
myTextField.border = true;
So now, when you test the movie, you'll be able to see where the text field is (it will be in the upper-left corner of the stage). It will have a border, as well as some text inside it.

You might also notice that the text does not fit horizontally inside the text field. The remaining part of the phrase we assigned to the text field can't be seen. If that's the case, then there are at least 2 ways that we can fix that:

  • activate the text field's word-wrapping feature using the wordWrap property of the TextField class
  • change the width of the text field using the width property of the TextField class

Let's go ahead and activate the word-wrapping feature:
var myTextField:TextField = new TextField();

addChild(myTextField);

myTextField.text = "Creating ActionScript 3 TextFields.";
myTextField.border = true;
myTextField.wordWrap = true;
The wordWrap property can be set to either be true or false. When set to true, the text inside the text field will automatically move down to the next line when there is no longer any horizontal space left. If there's still some horizontal space left, then the text will just continue along the current line.

If you wish to change the dimensions of the text field, then you can work with the width and height properties of the TextField class:
var myTextField:TextField = new TextField();

addChild(myTextField);

myTextField.text = "Creating ActionScript 3 TextFields.";
myTextField.border = true;
myTextField.wordWrap = true;
myTextField.width = 300;
myTextField.height = 50;
Here, I've changed the width to 300 pixels and the height to 50 pixels.

If you want to reposition the text field, then you can use the x and y properties of the TextField class in order to change the text fields x and y coordinates respectively:
var myTextField:TextField = new TextField();

addChild(myTextField);

myTextField.text = "Creating ActionScript 3 TextFields.";
myTextField.border = true;
myTextField.wordWrap = true;
myTextField.width = 300;
myTextField.height = 50;
myTextField.x = 75;
myTextField.y = 50;
Here, I've change the x coordinate to 75 and the y coordinate to 50.

Adding More Text to the Next Line
Let's go ahead and add more text to the current text that's already inside our text field. To do that, we will use the appendText() method of the TextField class like so:
var myTextField:TextField = new TextField();

addChild(myTextField);

myTextField.text = "Creating ActionScript 3 TextFields.";
myTextField.appendText("Here is another line of text.");
myTextField.border = true;
myTextField.wordWrap = true;
myTextField.width = 300;
myTextField.height = 50;
myTextField.x = 75;
myTextField.y = 50;
Here, we've added some more text using the appendText() method of the TextField class. But when you test the movie, you'll see that while the new text is added, it won't be placed in the next line. In order to place the new text in the next line, you can add a line break (\n) either at the end of the first line or at the beginning of the appended text. Let's go ahead and add a line break at the end of the first line:
var myTextField:TextField = new TextField();

addChild(myTextField);

myTextField.text = "Creating ActionScript 3 TextFields." + "\n";
myTextField.appendText("Here is another line of text.");
myTextField.border = true;
myTextField.wordWrap = true;
myTextField.width = 300;
myTextField.height = 50;
myTextField.x = 75;
myTextField.y = 50; 
Here, I've used the + operator to add a line break to the end of the first line. So when you test the movie now, you should see the appended text move down to the next line.

And those are some of the basics of working with AS3 TextFields

AS3: Enabling the user to submit the contents inside an input text field

In this lesson, we're going to learn how to add some ActionScript 3 functionality that will let a user submit the contents of an input text field by clicking on a button or pressing a keyboard key. We'll create a simple example of a Flash movie where the user can type in someone's name inside an input text field. When the user clicks on a button or presses a keyboard key, then we'll have Flash display a greeting (e.g. "Hello, John!") that will come out in another text field.

Go ahead and create a new Flash document so that we can begin.

Let's first create an input text field. Create a new layer for the ActionScript and type in the following code:
var myInput:TextField = new TextField();

addChild(myInput);

myInput.type = "input";
myInput.border = true;
myInput.x = 100;
myInput.y = 50;
myInput.width = 175;
myInput.height = 30;
Here, we've created a new instance of the TextField class named myInput. Go ahead and test the movie. You should see the input text field appear in the upper left region of your test movie.

Now that we have the text field, lets create a button symbol. So go ahead and use any of the drawing tools to draw any shape on the stage. You can place it anywhere. I'm going to draw a circle and convert it into a button symbol. And then I'll position it in the upper left region as well so that it will appear beside the input text field when we test the movie. Make sure that the button will not overlap with the text field. And make sure that you give this button an instance name by going to the Properties Inspector. I'm going to name this button submit_btn.

So when you test the movie again, you should have something like this:

Next, let's go ahead and create the text field that will display the greeting:
var myInput:TextField = new TextField();
var myGreeting:TextField = new TextField();

addChild(myInput);
addChild(myGreeting);

myInput.type = "input";
myInput.border = true;
myInput.x = 100;
myInput.y = 50;
myInput.width = 175;
myInput.height = 30;

myGreeting.border = true;
myGreeting.x = 100;
myGreeting.y = 100;
myGreeting.width = 175;
myGreeting.height = 30;
Here, we've created another instance of the TextField class named myGreeting. So when you test the movie now, another text field should appear right below the first one we created. This text field will be a dynamic text field since we did not specify a type (unlike the first one where we specified type = "input"). The default type is dynamic, which is why we don't need to specify it here. So this text field will not allow any input from the user. We'll simply use it to display the greeting. What we'd like is for the user type in a name inside the input text field first, and then click on the button in order to display the greeting in the dynamic text field. Let's go ahead and create the event handler for the button first:
myGreeting.border = true;
myGreeting.x = 100;
myGreeting.y = 100;
myGreeting.width = 175;
myGreeting.height = 30;

submit_btn.addEventListener(MouseEvent.CLICK, onClick);

function onClick(e:MouseEvent):void
{

}
Now that we have the AS3 event handler for the mouse click, let's take a look at the code that we need to write inside the event listener function's body.

In order to retrieve the contents of a text field, we can use the text property of the TextField class. So we can retrieve the contents of our input text field using:

myInput.text

And then we'll use the + operator to add it to the rest of the words and characters in our greeting phrase:

"Hello, " + myInput.text + "!"

Next, we'd like to display the greeting in our dynamic text field. In order to assign text to a text field, we'll use the text property of the text field class as well:

myGreeting.text = "Hello, " + myInput.text + "!";

So let's place that line inside the event listener function for the mouse click event:
submit_btn.addEventListener(MouseEvent.CLICK, onClick);

function onClick(e:MouseEvent):void
{
     myGreeting.text = "Hello, " + myInput.text + "!"
}
Go ahead and test the movie. Type in a name inside the input text field and then click on the submit button. After doing that, you should see the greeting come out in the dynamic text field.

Now let's go ahead and add the ActionScript 3 functionality that will also display the greeting when the user presses the enter key on the keyboard. First let's create the event handler. For keyboard events, the event listener is usually added to the stage. Since the stage is usually always active, then it's an ideal object that can be used to dispatch keyboard events. If you'd like to add an event listener for whenever a keyboard key is pressed, then you want to specify the KeyboardEvent.KEY_DOWN event. So let's go ahead and create the event handler for the key down event:
submit_btn.addEventListener(MouseEvent.CLICK, onClick);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);

function onClick(e:MouseEvent):void
{
     myGreeting.text = "Hello, " + myInput.text + "!"
}

function onKeyPressed(e:KeyboardEvent):void
{
     trace("A key has been pressed!");
}
So here, we've created the event handler for the key down event. The event listener function, which I've named onKeyPressed, has a trace statement inside it just so we can check if the event handler is working. Go ahead and test the movie. And make sure you disable keyboard shortcuts (test the movie first and then go to Control > Disable Keyboard Shortcuts to make sure that it's checked). Now, every time you press any keyboard key, you should see the phrase A key has been pressed! come out in the output window.

So now that it's working, we need to tell Flash to respond only when the ENTER key has been pressed. To do that, we can use an if statement that checks if the keyCode is equal to Keyboard.ENTER. The keyCode property refers to the last key that was pressed. This property can be accessed via the event object, which in our example is named e. And ENTER is a constant of the Keyboard class that refers to the enter or return key. So if the keyCode is equal to Keyboard.ENTER, then it means that it was the enter or return key that was last pressed. So let's go ahead and wrap the trace statement inside an if statement that checks for the keyCode:
function onKeyPressed(e:KeyboardEvent):void
{
     if(e.keyCode == Keyboard.ENTER)
     {          
          trace("A key has been pressed!");
     }
}
So now, if you test the movie, the trace statement only gets executed when the ENTER key is pressed. Pressing any other key will not yield any results.

And finally, all we have to do now is replace the trace statement in our key down event listener function with the line that will display the greeting inside the dynamic text field:
function onKeyPressed(e:KeyboardEvent):void
{
     if(e.keyCode == Keyboard.ENTER)
     {
          myGreeting.text = "Hello, " + myInput.text + "!";
     }
}
And that concludes this tutorial on writing ActionScript 3 code that will enable users to submit the contents of an input text field.

Friday, January 7, 2011

ActionScript 3: Convert Strings to Numbers

In this lesson, we are going to learn how to convert strings to numbers in AS3.

You can convert strings that are made up of numerical characters into actual Number data using the Number() constructor. The way it works is that you pass the String value to the Number() constructor, and in turn, this will create a Number version of the String that was passed to it.

Example:
var myString:String = "7";
var myNumber = Number(myString);
The first line creates a string - myString with a value of 7. The second line takes that String data and passes it to the Number() constructor, which creates a number version from it. And the converted value, which is now of the Number data type, is assigned to the variable named myNumber.

The syntax would be:
Number(String)

Why would I want to convert strings to numbers in AS3?
Let's say you have some String data made up of numerical characters, and you'd like to perform arithmetic operations using that data. If you don't convert the strings to numbers, then Flash won't allow you to perform arithmetic operations on them.

Here's an example. Let's say we have 2 strings that are made up of numerical characters:
var s1:String = "2";
var s2:String = "5";
And then we try to multiply them:
trace(s1 * s2);
Flash is going to give us this error message:
1067: Implicit coercion of a value of type String to an unrelated type Number.
This error is telling us that we are trying to force (or coerce) the String data to be used as Number data. You can only multiply numbers, NOT strings. So in the act of trying to multiply String data, we are implicitly coercing the values to change into Number data. We can't do that. We should explicitly convert the String data to Number data first, and then perform the arithmetic operation.

Here's another example. If we use the + operator on strings, then the strings will simply be joined together instead of the values being added to create a sum. Let's take a look:
var s1:String = "2";
var s2:String = "5";
trace(s1 + s2);
Here, we have two strings - s1 = "2" and s2 = "5". If we were to use the + operator on these two values, the result would be 25. The values of s1 (2) and s2 (5) will simply be joined together in the same way that letters are joined together in order to make words. If these were actual Number data, then the result of adding 2 and 5 would be 7 instead.

So if we want the values to be added to create a sum, then we'll need to use the Number() constructor to create number versions out of the strings:
var s1:String = "2";
var s2:String = "5";
trace( Number(s1) + Number(s2) );
Here, the strings s1 and s2 are each passed to the Number() constructor. This will create number versions from those strings, which can then be used in arithmetic operations. So here, the result will be 7, instead of the 25 we got from the previous example.

Here's another similar example. If you'd like to use the contents of a TextField instance in arithmetic operations, then you will also need to use the Number() constructor to create number values from those numerical characters inside the text field. Remember that characters inside a TextField are of the String data type, which is why we'll need to convert them to the Number data type for usage in arithmetic operations. For example:
// Assume that tf1 and tf2 are instances of the TextField class
// and that they have already been created and added to the stage
tf1.text = "2";
tf2.text = "5";
trace( Number(tf1.text) + Number(tf2.text) );
So here, in the last line, we are retrieving the values inside the text fields (tf1 contains "2", tf2 contains "5"). Those values are passed to the Number() constructor which will create number versions from those values. Those numbers can then be used in the arithmetic operation. The result in this example would be 7.

And that is how you can convert strings to numbers in ActionScript 3.

Wednesday, January 5, 2011

ActionScript 3 Number to String Conversion

In this lesson, we're going to learn how to convert numbers to strings in AS3.

If you you'd like to do ActionScript 3 Number to String conversions, then you can use the toString() method of the Number class.

Here is an example:
var myNumber:Number = 7;
var myString:String = myNumber.toString();
Here, we start off by creating a number - myNumber with a value of 7. In the next line, that number is converted into a string and is assigned to a variable named myString.

Why would I want to convert numbers to strings?
One example of how this can be useful is if you'd like to calculate some number value and then display it inside a text field.

For example:
var value1:Number = 7;
var value2:Number = 2;
var total:Number = value1 + value2;

myTextField.text =  total.toString();
// Assume that myTextField is an instance of the TextField class
// and that it has already been created and added to the stage
Here, we're creating two numbers (7 and 2), which are then added together (which sums up to 9). The sum is then displayed inside a text field. Without the toString() method, Flash will give us an error message if we try to assign a Number value inside the text field. The error message will state:
1067: Implicit coercion of a value of type Number to an unrelated type String.
This means that we are trying to force a number to be a string. A text field can not contain Number data so we will have to convert it to a String instead. Although, 9 as a Number looks the same as "9" as a String, you must still explicitly differentiate between the two inside your ActionScript 3 code. This makes AS3 number to string conversions pretty useful.
 
If the number is a decimal (e.g. .5), Flash will add a leading 0 when it performs the number to string conversion (i.e. .5 will become "0.5").

Also, the toString() method of the Number class accepts one parameter for the radix. The radix lets you specify which numeric base (from 2 to 36) to use when the number is converted into a string. For example, if you'd like the number to be interpreted as an octal (base 8), then you pass a value of 8 to the radix parameter:
var myNumber:Number = 14;
trace( myNumber.toString(8) );
If we used base 10, then this will still output 14. But since we specified base 8 instead, this will output 16. If no radix is specified, a default value of 10 (decimal) is used.

So that is how you do ActionScript 3 number to string conversions.