Thursday, September 23, 2010

Using the Button component: Part 4

Today's tutorial is all about toggle buttons.

Toggle buttons can be very useful in applications. For example, you can often encounter a button that toggles music on and off. Basically, a toggle button means a switch that remains pressed once you click it once, and releases when you click it the second time.

To make a Button component a toggle button, you have to set its property 'toggle' to true.

myBtn.toggle = true;

Now, your button is a switch. When it is toggled, its 'selected' property is true, and when its not toggled - 'selected' is false.

Here's a simple example:


And the code:

toggleButton.toggle=true
myField.text="Off"
toggleButton.addEventListener(MouseEvent.CLICK, toggleSwitch);

function toggleSwitch(MouseEvent):void{
myField.text = (toggleButton.selected)?"On":"Off";
}

As you can see, I used the short if statement ( (condition)?if-true:if-false ) to decrease the number of lines in my code. It is just the same as if...else.

We can turn it into something more complicated. In the next example, the icon of our button depends on whether the button is toggled or not.


Code:

toggleButton.setStyle("icon", redIcon);
toggleButton.toggle=true
toggleButton.addEventListener(MouseEvent.CLICK, toggleSwitch);

function toggleSwitch(MouseEvent):void{
toggleButton.setStyle("icon" , ((toggleButton.selected)?greenIcon:redIcon) );
}

Thanks for reading!

Related:

Using Button component part 1
Using Button component part 2
Using Button component part 3
Using Button component part 5

No comments:

Post a Comment