ActionScript 3: Basic Content Loading

as3-basic-content-loading_post
In this tutorial, we will learn how to do content loading with an XML file, a common file format that is used to feed data into Flash applications (among other things), and lay some groundwork for more advanced Flash programming with the use of AS3.

For this example we will create all of the content through XML loaded via ActionScript code, although there are other methods that achieve the same effect.

This tutorial assumes that you are using Flash CS4 on a Windows or Mac computer. Source code can be found at the end of this article.

Part One: Setup

First, create a new Flash project. Make sure that it is using ActionScript 3. Height and width can be whatever size you like. I am going to use a 590px width and 270px height movie running at 30FPS.

Next, we will need to make the ActionScript 3 file required for this class to run (see the full tutorial about using classes here).

Attach the FLA to the class file and then open up the ActionScript file. Place this inside the ActionScript 3 file to set-up the basic skeleton of the file including the imports and constructor:

/* 	BasicContentLoading.as
//	electrokami.com
//	BasicContentLoading tutorial
//	5.31.2010
*/
package com.electrokami{
	import flash.display.MovieClip;
	import flash.display.*;
	import flash.net.*;
	import flash.events.*;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	
	public class BasicContentLoading extends MovieClip{
		/*** private vars ***/
		private var xmlFile:String = "basic_content_loading_data.xml";
		private var xmlIsLoaded:Boolean = false;
		private var xmlObject:XML;
		private var contentItemsArray:Array = new Array();
		private var itemSpacing:Number;
		private var thePrompt:String;
		private var theText:TextField;

		public function BasicContentLoading():void{
			trace("[load_content]... init");
			theText = new TextField();
			theText.autoSize = TextFieldAutoSize.LEFT;
			theText.text = "Loading content...";
			theText.x =theText.y = 250;
			addChild(theText);
			initXML();
		}
		private function initXML():void{
		}
		private function initElements():void{	

		}
	} // end class
} // end package

Feel free to change the heading to reflect your own details

You will notice that we are using quite a few imports:

package com.electrokami{
	import flash.display.MovieClip;
	import flash.display.*;
	import flash.net.*;
	import flash.events.*;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;

We are also going to utilize the text library in order to present text to the user. We are also using the event and net/url loading libraries to open and read an xml file.

Need to catch up on your XML? Check out this tutorial about how to create and customize your very own XML file for Flash.

Speaking of the XML file (seen above as “basic_content_loading_data.xml”), don’t forget our content!

<? xml version="1.0" encoding="UTF-8" ?>
<content spaceBetweenItems="147" prompt="Pick your favorite Beatle!">
<answers>
    <answer>
    <thumbPath>beatles_John.jpg</thumbPath>
    <theResponse>You chose John!</theResponse>
    <responseColor>0xff0000</responseColor>
    </answer>
    <answer>
    <thumbPath>beatles_Paul.jpg</thumbPath>
    <theResponse>You chose Paul!</theResponse>
    <responseColor>0x000066</responseColor>
    </answer>
    <answer>
    <thumbPath>beatles_George.jpg</thumbPath>
    <theResponse>You chose George!</theResponse>
    <responseColor>0x006633</responseColor>
    </answer>
    <answer>
    <thumbPath>beatles_Ringo.jpg</thumbPath>
    <theResponse>You chose Ringo!</theResponse>
    <responseColor>0x666666</responseColor>
    </answer>
</answers>
</content>

Here is the data we will be using to run this app – a simple poll about which Beatle is your favorite!

At this point you should do a test run to make sure that you have everything correct and functional. Press CTRL+Enter (on Mac press CMD+Enter), or press the menu button Control and click “Test Movie”.

The movie should be white and the trace should show up on your output tab. There should be no errors.

Part Two: Get That Content!

Now we will flesh out the initXML() function. We need to first check if the XML file is loaded (in case this file is part of a larger Flash based application) and then proceed to load it and parse the data:

private function initXML():void{
    if(xmlIsLoaded){trace("xml loaded");}
    else{
        var xmlLoader:URLLoader = new URLLoader(new URLRequest(xmlFile));
        
        xmlLoader.addEventListener(Event.COMPLETE, function():void{
            xmlIsLoaded = true;
            xmlObject = new XML();
            xmlObject.ignoreWhitespace = true; 
            xmlObject = new XML(xmlLoader.data);					
            trace("[load_content]... load xml data");
            itemSpacing = Number(xmlObject.attribute("spaceBetweenItems"));	
            thePrompt = String(xmlObject.attribute("prompt"));	
            
            for(var i:uint = 0; i < xmlObject.answers.children().length(); i++){
                contentItemsArray[i] = new Object(); 
                contentItemsArray[i].thumbPath = xmlObject.answers.children()[i].thumbPath.toString(); 
                contentItemsArray[i].theResponse = xmlObject.answers.children()[i].theResponse.toString(); 
                contentItemsArray[i].responseColor = xmlObject.answers.children()[i].responseColor.toString();
            }
            theText.text = thePrompt;
            initElements();
        }); // end xmlLoader Event
    } // end else
}

This function will load and parse a specific XML file structure (as seen above in the XML source).

Some key parts to pay attention to:

itemSpacing = Number(xmlObject.attribute("spaceBetweenItems"));	
thePrompt = String(xmlObject.attribute("prompt"));		

This will grab the attribute data that we put inside the content tag.

for(var i:uint = 0; i < xmlObject.answers.children().length(); i++){
    contentItemsArray[i] = new Object(); 
    contentItemsArray[i].thumbPath = xmlObject.answers.children()[i].thumbPath.toString(); 
    contentItemsArray[i].theResponse = xmlObject.answers.children()[i].theResponse.toString(); 
    contentItemsArray[i].responseColor = xmlObject.answers.children()[i].responseColor.toString();
}

And this will loop through the each answer, grab all the neccessary data, and store it in the class instance variable declared as contentItemsArray.

And now at this point you should do another test run to make sure that you have everything correct and functional. Furthermore, the text inside the XML attribute “prompt” should display in the bottom of the Flash file:

Get Adobe Flash player

Part Three: Show That Content!

Finally time to show off our dynamically loaded content! You will see that at the end of the initXML() function we call another function named initElements(). This will be the method that takes the content and presents it to the user:

private function initElements():void{	
    trace("[load_content]... showing content");
    var totalItems = contentItemsArray.length - 1;
    for(var i:uint = 0; i <= totalItems; i++){				
        // load thumb
        var itemThumbLoader:Loader = new Loader();				
        var fileRequest:URLRequest = new URLRequest(contentItemsArray[i].thumbPath);
        itemThumbLoader.load(fileRequest);
        var contentItem:MovieClip = new MovieClip();
        contentItem.x = i * itemSpacing;
        contentItem.y = 40;
        contentItem.name = String(i);
        contentItem.addChild(itemThumbLoader);
        contentItem.buttonMode = true;
        contentItem.addEventListener(MouseEvent.CLICK, contItemClicked);
        this.addChild(contentItem);
    }
}
public function contItemClicked(e:Event):void{
    theText.textColor = uint(contentItemsArray[Number(e.currentTarget.name)].responseColor);
    theText.text = contentItemsArray[Number(e.currentTarget.name)].theResponse;
}

Looks like a mouthful huh? Let’s take a look!

Essentially we are looping through the array of XML data and grabbing the image and loading it into the Flash movie:

// load thumb
var itemThumbLoader:Loader = new Loader();				
var fileRequest:URLRequest = new URLRequest(contentItemsArray[i].thumbPath);
itemThumbLoader.load(fileRequest);

And then we are assigning a name and position to dynamically created MovieClip objects:

var contentItem:MovieClip = new MovieClip();
contentItem.x = i * itemSpacing;
contentItem.y = 40;
contentItem.name = String(i);

And then we are assigning the loaded image (in this case images of each of the four Beatles) and attaching them to the same dynamically created MovieClip:

contentItem.addChild(itemThumbLoader);

Next we make this dynamic MovieClip into a clickable element by using the attribute “buttonMode” and tell the Flash player to create an EventListener to register any click on this element:

contentItem.buttonMode = true;
contentItem.addEventListener(MouseEvent.CLICK, contItemClicked);

Lastly we will add this XML driven MovieClip onto the stage with a simple command called addChild(), which is akin to “placing” the element on the stage with all of the above conditions attached to it.

this.addChild(contentItem);

As you can also see, we added in the function contItemClicked() so that any clicks on our super dynamic Beatles content will start up a callback function that will do stuff. In this case, the stuff being done is changing the textColor of the main text element (aptly titled theText) as well as updating the text with the response from our XML file:

public function contItemClicked(e:Event):void{
    theText.textColor = uint(contentItemsArray[Number(e.currentTarget.name)].responseColor);
    theText.text = contentItemsArray[Number(e.currentTarget.name)].theResponse;
}

By using the pre-assigned target name as an index variable for the array, we are able to grab the data from the correct relevant Beatles’ response text.

What is really cool about what we just did is that we allowed ourselves to dynamically call the MovieClip during the EventListener therefore allowing us to quickly modify the Flash stage and grab the necessary data from that specific array item with minimal effort.

Take a look at the results, and bask in the glow of your dynamic content loading Flash movie!

Get Adobe Flash player

Well, that about sums up this tutorial, thank you for taking the time to read this article! Feel free to ask questions or comment on this tutorial- any and all opinions are acceptable.

And, as promised, here is the source file for this tutorial:

Download: basic_content_loading.zip

Related Posts