Creating a toggle button

How to

Create a toggle button in your application.

Solution

Construct a button variable in the root of your class

private var myButton:Button = new Button(); 	
// Placing this at the class root allows other 
// application elements to reference it.

Initialize your button's attributes

// Location and size
myButton.setPosition(200,200);
myButton.width = 100;
myButton.height = 50;

// Toggle or click
myButton.toggle = true;

// Call myButtonEvent function when button is clicked.
myButton.addEventListener(MouseEvent.CLICK, myButtonEvent);

//Add button to the stage.
this.addChild(myButton);

Create the function that is called by your button's click event

private function myButtonEvent(event:MouseEvent) {
	// Output click event to console. myButton.selected 
	// returns true when button is in the down state.
	trace ("myButton has been clicked, current toggle state is:" + myButton.selected);
}

Build requirements

You must include the following classes in your project:

import qnx.fuse.ui.buttons.Button;
import flash.events.MouseEvent;

Discussion

When you create a toggle button, you declare the Button variable and then set its attributes. To add functionality, add a MouseEvent.CLICK listener function to perform any actions that are defined in the function when the button is clicked. You can also reference the state of the button anywhere in the class by using the selected property.

comments powered by Disqus