Requirements    
Prerequisite knowledge Required products Sample Files
Basic understanding of the Flash authoring
environment and prior experience coding in Flash Lite 2.0 is recommended.
 
 
User Level    
Beginning
   

 

In this tutorial I'll describe how to build a simple but useful List component for Flash Lite applications. You may be familiar with the ActionScript 2.0 List component that ships with Adobe Flash CS4 Professional. Due to the memory and processor constraints of the mobile environment, that component isn't practical for use in Flash Lite applications. This article includes the sample files for the completed custom List component. The sample project can be extended and updated to tailor any part of it to fit the needs of your Flash Lite mobile application.
 

Understanding how the List component works

By definition, a List component is a scrollable collection of items that allows the user to choose a single or multiple list items. List components are scrollable because there are times when the amount of data exceeds the amount of screen real estate and all of the list items cannot be displayed on the device at once. From a Flash perspective, the items in the list will be displayed in separate movie clips. All of these list item movie clips are contained within the list movie clip. Users can navigate the list by pressing the up or down soft keys on their device's directional pad, and they can select an item by pressing the center soft key (which is sometimes labeled Enter).
However, due to resource constraints of mobile devices, creating a movie clip for every data element in your list could result in poor performance, out-of-memory errors and crashes on some lower-end devices. To resolve this issue, the List component created in this sample project will only use as many movie clips as are visible at any one time, and logic in the ActionScript code updates the values shown in those clips when necessary.
This diagram represents a data set of eight elements, and a list that can display four of those elements at once to the user. This illustrates how the list items work in relation to the data (see Figure 1):
An example depicting the entire list of data and the viewable area.
Figure 1. An example depicting the entire list of data and the viewable area.
 

In the diagram above, the item with focus represents the initial state of the list, before any user interaction has occurred. The list displays the first four items from the data set, and the first item in the list has focus by default—it is the list item that would be selected if user pressed the select soft key on their device. As the user uses the up and down soft keys to navigate through the list, the logic in the ActionScript code determines whether to change the current focus to a different list item movie clip, or whether to change the data that is currently being displayed to the user.

The different states of the list shown below are the various situations to consider in making that decision (see Figure 2):

Considering the different possible states of the List component.
Figure 2. Considering the different possible states of the List component.
 
In Figure 2A, if the user presses the down soft key, it is only necessary to change which movie clip has focus. If the user presses the up soft key, the logic will re-populate the list with a new range of data because there isn't a list item movie clip above the one that currently has focus. This means that instead of showing Data2 through Data5, when the user presses the up soft key, the list changes to display Data1 through Data4.
In Figure 2B, the situation is exactly the reverse of Figure 2A. Pressing the up soft key requires the logic to change the focus to a different list item. Pressing the down soft key will result in changing the list to show Data3 through Data6.
In Figures 2C and 2D, it doesn't matter whether the user presses their up or down soft keys; all the List component needs to do is change which movie clip currently has focus.
Of course, it is also necessary to add the logic to ensure that the user cannot scroll beyond the very top or very bottom of the list of data.
Now that you have a clear concept of how the List component works and how the user can interact with the list, it's time to begin building it. In the next section, I'll provide the step-by-step instructions to begin developing the sample project.

Getting started with the sample project

 

If you haven't already, be sure to download the sample files provided on the first page of this article.
In Flash CS4, open the file named list_start.fla from the sample files folder. We'll start by using the sample movie clips I created for this article—later you can customize the List component for your own projects. After opening the file, you'll see the list displayed on the Stage (see Figure 3):
 
The initial state of the sample project.
Figure 3. The initial state of the sample project.
 
Look at the items in the Library. Then review the elements of the project by double-clicking on the movie clips to see how they are nested. Use the Property inspector to identify the instance names. There are two main movie clips on the Stage: the list itself and a scrollbar. The list movie clip contains multiple instances of the list item movie clip used to display the data. The list item movie clip instances are named listItem0 through listItem7, for a total of eight visible list items. Double click on the mc.listItem movie clip in the Library to see its Timeline. Each list item movie clip contains keyframes labeled on and off. When an item has focus, it will display the graphics that exist at the on keyframe, otherwise it will display the contents of the off keyframe. There is also a dynamic text field that is used to display the data from the array.
The scrollbar contains the scrollbar track, as well as the slider. The slider is a nested movie clip. In the last section of this article I'll describe how to change the slider's size and position depending on how many elements are in the array of data.
Spend some time analyzing the structure of the movie clips and their instance names. After you've become familiar with these movie clips, you're ready to begin adding the ActionScript to populate the list with data. In the next section, I'll provide the instructions on how and where to add the code.
 

Adding ActionScript to initialize the list and populate it with data

 

In this section, I'll describe how to add the code to initialize the list and change it in response to user input.

Setting the data source and list variables

In the main Timeline, click on Frame 1 of the ActionScript layer. Open up the Actions panel by selecting Window > Actions. We'll use an array of 26 string elements as the data source for testing the List component. Copy and paste the following code into the Script window:
var listDataArray:Array = ["Alice", "Betty", "Carl", "David", "Emily", "Frank", "George", "Heather", "Ivy", "John", "Kathy", "Leon", "Michael", "Nicholas", "Octavia", "Pauline", "Quincy", "Richard", "Stanley", "Trevor", "Ursula", "Virginia", "Wanda", "Xavier", "Yvonne", "Zoe"];
 
Next, add this code snippet directly beneath the previous array code:
 
// track which item from listDataArray is shown in the first list item movie clip var firstVisibleListItem:Number = 0; // list item that currently has focus var listItemWithFocus:Number = 0; // constants. TOTAL_LIST_ITEM_CLIPS may be changed // in initializeList(). MAX_VALUE_OF_FIRST_LIST_ITEM // is set in initializeList(); var TOTAL_LIST_ITEM_CLIPS:Number = 8; var MAX_VALUE_OF_FIRST_LIST_ITEM:Number;
The firstVisibleListItem variable keeps track of the index of the array element that is visible in listItem0. This value is used as the basis for the function that will populate the list items with data from the array. This value is set to 0 so that when the list is first displayed, the first visible item is the first element from the array of data.
The listItemWithFocus variable keeps track of which of the eight list item movie clips currently has focus. Again, the script initializes the value to 0 so that the first list item has focus when the list is created.
The constant TOTAL_LIST_ITEM_CLIPS will specify the number of list item movie clips in the list. As you can see from counting the list items inside the list movie clip, there are eight movie clips in total. You will use this number for various purposes, such as when you populate the list with the data. If you customize the list by changing the number of list item movie clips, you will also have to change the value of this constant.
The last line of code creates a constant that specifies the largest index of the element from the data that can be displayed in listItem0. You'll set the value of this constant when you initialize the list. I'll explain the purpose of this variable in the next section.

 

Initializing the list

 
Copy and paste the following function below the existing code in the script window. This function will be called when you want to set up the list:
function initializeList() { // check to see if we need to make this constant a smaller number // (if we have fewer data elements than list item movie clips) if (listDataArray.length < TOTAL_LIST_ITEM_CLIPS){ TOTAL_LIST_ITEM_CLIPS = listDataArray.length; } // value of this constant can only be set after data is loaded MAX_VALUE_OF_FIRST_LIST_ITEM = listDataArray.length - TOTAL_LIST_ITEM_CLIPS; // call the functions to set up the list and the scrollbar setScrollBar(); populateList(); setListFocus(); }
The first part of the function checks whether the list data contains fewer elements than can be displayed on the screen. In that situation, you'll want to make TOTAL_LIST_ITEM_CLIPS equal to the number of elements in the array. This setting will prevent the user from scrolling to empty list items. Although in this example there are more data elements than list item clips, you may encounter situations where this is not the case. (Technically speaking, it's not a best practice to be changing the value of a constant—otherwise it's not really a constant! However, in the constrained mobile environment, this approach is the simplest and most efficient.)
The next part of the function sets the value of MAX_VALUE_OF_FIRST_LIST_ITEM. In this hypothetical scenario, the user has scrolled down to the bottom of the list (see Figure 4):
The focus is at the end of the list.
Figure 4. The focus is at the end of the list.
 
In this case, you don't want the list to change if the user presses the down soft key again, so you need a way to test for this situation. This is the purpose of the value of MAX_VALUE_OF_FIRST_LIST_ITEM.
Remember that firstVisibleListItem stores the index of the element visible in listItem0. When the user presses the down soft key, you can check to see if firstVisibleListItem is less than MAX_VALUE_OF_FIRST_LIST_ITEM. if it is, you know that there is more data to display. If the two values are equal, you know that you're at the end of the list, and the code should not respond to subsequent down soft key presses. You can calculate MAX_VALUE_OF_FIRST_LIST_ITEM by subtracting TOTAL_LIST_ITEM_CLIPS from the total number of elements in the data array.
The next step is to call a number of other functions to complete the set-up of the list. Each of these functions, as well as the other code required to make the list work, will be discussed in the next section of this article, and then we'll finish off the sample project by discussing the scrollbar-related code at the end.

 

Populating the list

Add the following function to Frame 1 of the ActionScript layer, beneath the other existing code:
// iterate through all of the list item movie clips inside the list and // assign the required value from the data source to the list item's text // field function populateList() { var i:Number = 0; while (i < TOTAL_LIST_ITEM_CLIPS) { var targetMovieClip:MovieClip = list["listItem" + i]; var dataToAssign:String = listDataArray[firstVisibleListItem + i]; targetMovieClip.listTextField.text = dataToAssign; i++; } moveScrollBar(); }
The populateList function contains the code that will actually display the data in the list items. It consists of a simple while loop that gets the required data from the data array and assigns it to the proper list item movie clip.
Because firstVisibleListItem stores the index of the data element displayed in the first list item movie clip, you can use this value to determine what data should be shown in all of the list item movie clips. If, for example, firstVisibleListItem = 0, you need to display the value of listDataArray[0] in listItem0, listDataArray[1] into listItem1, and so on. If firstVisibleListItem = 3, you would want to display listDataArray[3] through listDataArray[10]. In general, the calculation firstVisibleListItem + i will determine what data should be displayed in each list item.
The next step in the loop is to display the data obtained from the array in the appropriate list item. In this case, you assign the value of dataToAssign to the text property of the dynamic text field in the list item movie clip. If you're working with a more complex set of data (for example, if you want to display a thumbnail image alongside the text), this is where you would adapt the code to suit your needs.
 

Changing the list item focus

 
Next, copy and paste this function below the other code in the Actions window:
function setListFocus() { var targetMovieClip:MovieClip = list["listItem" + listItemWithFocus]; targetMovieClip.gotoAndStop("on"); }
The setListFocus function sets the list item movie clip with focus to the on keyframe. Since this function turns on the proper list item clip, it is also necessary to add the complimentary function to turn off the focus of a list item movie clip whenever it is changed. Copy and paste the following code at the bottom of the Actions window:
function clearListFocus() { var targetMovieClip:MovieClip = list["listItem" + listItemWithFocus]; targetMovieClip.gotoAndStop("off"); }
At this point, the logic has been added to retrieve the data from the array, initialize and populate the list with the data. The focus of the list item movie clips has been set to the default selection of the top item in the list, and we've added the code that allows the focus to be changed (which also changes the list item graphically, using the on and off keyframes in the list item's Timeline).
In the following section we'll begin adding the code to create interactions that occur based on the user's input, so that they can step through the items in the list and select the desired item.
In this section, I'll provide the steps to make the interface interact when the user presses the soft keys on their handset. We'll need to address the ability to jump up and down in the list, as well as allowing the user to select the list item that they wish to choose.

 

Adding the logic that is triggered when the user presses the down key

 
Copy and paste this code at the bottom of the Actions window:

Building the navigation to respond to user interaction

 

function pressDown() { if (listItemWithFocus < TOTAL_LIST_ITEM_CLIPS - 1) { clearListFocus(); listItemWithFocus++; setListFocus(); } else if (firstVisibleListItem < MAX_VALUE_OF_FIRST_LIST_ITEM) { // bottom list item has focus, but we're not at the end of // the list, so we need to repopulate the list with new data firstVisibleListItem++; populateList(); } }
If you recall the earlier discussion of how the List component will function, you'll remember that we need to check for two possibilities when the down soft key is pressed:
  1. If the list item movie clip with focus is not the bottom one, change the focus to a different list item clip. This is accomplished by checking to see if listItemWithFocus is less than TOTAL_LIST_ITEM_CLIPS - 1 (which, in this specific example, is 7). If it is, you can change which list item has focus by clearing the focus on the item that is currently highlighted, increment the value of listItemWithFocus, and then set the focus on the following list item.
  2. If that test fails, then you know that the last list item movie clip has focus. This means it's necessary to change the data being displayed. This is accomplished by incrementing the value of firstVisibleListItem, and then calling the populateList() function again.
If both of these conditions fail, then you know that the focus is on the last list item in the list. Since the user has reached the very end of the list, the functions do not need to take any action.

 

Adding the logic that is triggered when the user presses the up key

 
Now we can add the function that is called when the user presses the up key on their handset. Copy and paste the following code and add it to the bottom of the Actoins window:
function pressUp() { if (listItemWithFocus > 0) { clearListFocus(); listItemWithFocus--; setListFocus(); } else if (firstVisibleListItem > 0) { // top item has focus, but we're not at the top of // the list, so we need to repopulate the list with new data firstVisibleListItem--; populateList(); } }
The code listed above also checks for two possible conditions:
  1. If listItemWithFocus is greater than 0, change which list item has focus, rather than re-populate the list with new data from the array. This code is similar to the first condition checked in the pressDown function, except that you are decrementing the value of listItemWithFocus, because you are moving up the list.
  2. If that condition fails, then check to see if firstVisibleListItem is greater than 0. If it is, change the data being displayed to represent scrolling up through the list. This is similar to the second condition being checked in the pressDown function.
And of course, if both of these cases fail, then you know the user has reached the very top of the list, so it is not necessary to take further action.
Adding the logic that is triggered when the user presses the enter key
Finally, add this code to the bottom of the existing code, which will be called when the user presses the enter key (center soft key) to select an item from the list:
function pressSelect() { var arrayIndex:Number = firstVisibleListItem + listItemWithFocus; trace("Position in the array is: " + arrayIndex); trace("The value of that element is: " + listDataArray[arrayIndex]); }
This calculates the index of the selected item by adding the value of listItemWithFocus to the value stored in the variable firstVisibleListItem. In this example, this calculation will return a value from 0 to 25, which corresponds to the possible index values for a data array of 26 elements. When you are using the list in your application, this is where you would add the code you want to execute when the user selects a list item, instead of simply tracing the value of the selected list item to the Output window.

Creating the key listener

Since we've just added the pressUp, pressDown and pressSelect functions, we need to set up a key listener to call these functions when user interaction occurs. Add this code after the existing code:
var keyListener:Object = new Object(); keyListener.onKeyUp = function() { var keyPressed:Number = Key.getCode(); switch (keyPressed) { case (Key.DOWN) : pressDown(); break; case (Key.UP) : pressUp(); break; case (Key.ENTER) : pressSelect(); break; } }; Key.addListener(keyListener);
The script above is standard key listener code, which calls the appropriate function in response to key presses on the handset. To learn more, see the Flash Lite 2.x and 3.x ActionScript Language Reference section on key listeners.
Now we just need to add the last bit of code to initialize the list so you can test your List component. Add this code to the very end of the Actions window:
Save the file. Test your work by selecting Control > Test Movie or by pressing Command-Return (Mac) or Control-Enter (Windows). Testing this mobile application causes Adobe Device Central CS4 to launch. When it opens, make sure that you've selected a Flash Lite 2.0-enabled device. Press the up and down soft keys to scroll through the list of items. Press Enter (or the center soft key) to display the value of the currently selected list item to the Output window.
Note: If the Output window is not open, you can open it by selecting Window > Flash Output in Device Central CS4, or by pressing Command-T (Mac) or Control-T (Windows).
The interface is responding to the soft key presses, but of course the scroll bar isn't working yet. In the last section of this article, I'll describe how to set up the scroll bar to orient users as they scroll through the list of items.
// initialize the list and scrollbar initializeList();
The scrollbar is an integral part of the List component, and it offers valuable insight that enhances the user's experience. As the user moves up and down through the list of items, the scrollbar moves up and down to orient users to their current location in the list of data. It also provides the user with a sense of how much of the list is visible, relative to the total size of the list. To make the scrollbar work, we need to add two more functions: one to set up the scrollbar's functionality, and another that will update the position of the slider when a new list item receives focus.

Adding the scrollbar functionality

In Flash CS4, add this code after the pressSelect function and before the key listener is initialized (it could be added at the end of the Actions window as well, but this way all of the List-related functions are kept together):

Setting up the scrollbar

function setScrollBar() { var spacePerItem:Number = scrollBar._height / listDataArray.length; var scrollBarHeight:Number = spacePerItem * TOTAL_LIST_ITEM_CLIPS; scrollBar.slider._height = scrollBarHeight; scrollBar.sliderMoveAmount = spacePerItem; }
The code above accomplishes two related goals: it sets the height of the slider and it determines how many pixels the slider should move up or down as the user navigates through the list. The height of the slider is set to a percentage of the height of the scrollbar. This percentage is equivalent to the percentage of elements from the data array that are visible at any one time. In this example, there are 8 out of a possible 26 elements visible, so the height of the slider should be 8/26ths of the height of the total scrollbar area. First, the script calculates the
spacePerItem
, then multiplies that value by 8 to determine the height of the slider.
The value of spacePerItem is also the amount by which the slider should move when the scrollbar needs to move up or down. Storing that value inside the scrollbar movie clip makes it available for later use, and it also makes it easier to repurpose the scrollbar in other applications.

Moving the scrollbar slider

Here's the last piece of code you need to enter. Paste it after the setScrollBar() function:
function moveScrollBar() { scrollBar.slider._y = firstVisibleListItem * scrollBar.sliderMoveAmount; }
The function above sets the _y value of the slider based on the value of firstVisibleListItem. This means that the slider will move only when firstVisibleListItem changes, which occurs when the list items movie clips are re-populated with data. In these situations,either the first or the last list item movie clip has focus. Because the actual movie clip that is on does not change, it may not be immediately clear to the user that anything has changed. Moving the scrollbar slider in these situations helps to visually reinforce the fact that the display has updated in response to the user's actions by pressing the soft keys.
Test your application and see how it works. If any of the steps are still unclear, try adding some trace() statements in the various functions to see how the variables change depending on the current state of the list. If you're getting errors you can't fix or the List component isn't working as expected, compare your code to the code in the list_finished.fla located in the sample files folder.
You now have a fully functional List component with a scroll bar to use within mobile applications. This component can now be extended and integrated into your mobile applications to create an interface for navigating a list of data.
 

Where to go from here

 
The custom List component is completely customizable—you can change how the list item looks to match the design of your application. For example, you can:
  • Update the look and feel of the list item movie clip and/or the scrollbar as desired.
  • Remove elements from the List component, or make them smaller, to make room for a heading and/or soft key text. Just remember to change TOTAL_LIST_ITEM_CLIPS to the appropriate value if necessary, and ensure that the list item movie clips are numbered sequentially. Review the file named list_customized.fla from the sample files folder to see an example of how to do this.
  • Enhance the list item movie clip. Currently the list item only displays a line of text, but the movie clip could be modified to display a more complex data set, such as thumbnail images with descriptions. To do this, you'll need to consider how to store your data in listDataArray. You'll also need to update the populateList() function so that your image and text are properly displayed.
  • Change the list from a single selection to a multiple selection component. The List component created in this sample project only allows the user to select one item at a time, but you may encounter situations where you want the user to select more than one item from the list.
And here are some other ways to enhance the user experience of the List component:
  • Modify the list item movie clip and the associated code so that the list items play an animated transition when they receive focus.
  • Add code to allow users to page backward or forward through the list by pressing the left or right keys on the directional pad. This feature would be particularly useful to implement if your data set contains a large number of elements.
  • Modify the list to add animation as the user scrolls through the items, instead of jumping from one static position to another as it does in this example.
I hope you've found this article to be interesting and useful. If you have any questions about the List component, please feel free to contact me.
Continue to hone your Flash Lite development skills by checking out the many excellent articles and sample projects available at the Mobile and Devices Developer Center. And be sure to visit the Flash Lite section of the Mobile and Devices Developer Center to get more information about developing applications for mobile devices.