Monday, May 26, 2008

Toggle Buttons

Toggle buttons are a common variation on simple buttons. An easy example is a play button that changes to a pause button when clicked and vice versa. From the previous post, the ActionScript class SimpleButton already has toggle button capabilities. This post will demonstrate how to use.

A toggle button requires three additional states: toggled up, toggled over, and toggled down. Three additional images will be supplied for the toggled state.
  1. Right click and save this image () as green_rect.png in the src directory. This will be our "toggled up state".
    On my machine, the full path is:
    /home/kca/workspace/hello_world/src/
  2. Right click and save this image () as light_green_rect.png in the src directory. This will be our "toggled over state".
  3. Right click and save this image () as very_light_green_rect.png in the src directory. This will be our "toggled down state".
  4. Copy and paste this XML into asset.xml in the src directory
  5. At the command prompt, run this command in the src directory:
    swfmill simple asset.xml asset.swf
  6. This will rebuild the asset library. A new SWF file should now exist in the src directory called asset.swf.
  7. Double click source file Application.as to edit
  8. At the bottom of function init, add this code:
    var my_button:SimpleButton =
    SimpleButton.create(this, "my_button", 25, 300,
    "asset_red_rect", "asset_pink_rect", "asset_light_pink_rect") ;
    my_button.enable_toggle_button("asset_green_rect", "asset_light_green_rect", "asset_very_light_green_rect") ;
    var char_counter:Number = 1 ;
    var instance:Application = this ;

    my_button.onRelease = function() {

    if (my_button.is_toggled()) {

    instance._hello_world_text_field.text = hello_world_text.substring(0, char_counter).toLowerCase() ;

    } // end if (my_button.is_toggled())

    else // if (!my_button.is_toggled())
    {

    instance._hello_world_text_field.text = hello_world_text.substring(0, char_counter) ;

    } // end else if (!my_button.is_toggled())

    ++char_counter ;
    if (char_counter > hello_world_text.length) {

    char_counter = 1 ;

    } // end if (char_counter > hello_world_text.length)

    } ; // end my_button.onRelease = function()
    Save the file, and the SWF file is automatically rebuilt by Eclipse. Click to see the new red button in the bottom left. Move the mouse over and the color changes to pink; press the mouse down and it becomes light pink.
  9. Click the button to toggle to green. The words "Hello, World!" spelled, one character for each click, but each toggle converts between lower case and mixed case.


No comments: