Example: List Display Adapter | 195
var listField = new TextField( );
listField.x = 20;
listField.y = 20;
var sList:String = "Bread";
sList += "\r" + "Butter";
sList += "\r" + "Cheese";
listField.text = sList;
addChild(listField);
This works, but what if you want to delete an item from the list? You essentially have
to recreate the list again. Thinking more about this, it becomes apparent that hold-
ing the list items in an array and splitting the array to create a string separated by
return characters would be a better option. This would require more code, and our
little code block ceases to become a “snippet” and screams out for a generic solution.
Wouldn’t it be nice to have a reusableListDisplayFieldwhere you can add one list
item at a time? It would function very much like aTextFieldwith built-in list item
functionality. This is a good context in which to develop an adapter because we’ll be
using an existing class and converting its interface to fit a new context.
The Existing Class
TheTextFieldclass is used for text display and input in ActionScript 3.0. We will
use it as the existing class. It has a detailed interface with many properties and meth-
ods that allow low-level manipulation of rendered text. The ActionScript 3.0 docu-
mentation (accessible online) describes this class at length.
Interface Conversion
We need to convert theTextFieldclass interface to enable adding and deleting list
items as required in the new context. ThedeleteItemAt(n:uint)method defines a
return type signifying the success or failure of the operation. The interface also
defines a method to clear the field. TheIListDisplayinterface in Example 5-13
defines the new target interface.
Example 5-13. IListDisplay.as
package
{
public interface IListDisplay
{
function addItem(s:String):void;
function deleteItemAt(n:uint):Boolean;
function clear( ):void;
}
}