Creating toggle and emphasized Button controls in Flex

Pretty basic stuff, but if you’ve never used a toggle button in Flex or Flash, you may find this useful. The following example creates two Button controls. The first button sets the toggle property to true and determines whether the button is currently selected by watching the button’s selected property. The second button simply sets the emphasized property to true, which gives the button a nice visible border, making it stand out a little more than the other buttons. This is great for highlighting a default button in a form.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/08/20/creating-toggle-and-emphasized-button-controls-in-flex/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Number id="buttonWidth">200</mx:Number>

    <mx:Button id="button1"
            label="toggle= true; selected = {button1.selected}"
            toggle="true"
            width="{buttonWidth}" />

    <mx:Button id="button2"
            label="emphasized = true"
            emphasized="true"
            width="{buttonWidth}" />

</mx:Application>

View source is enabled in the following example.

3 thoughts on “Creating toggle and emphasized Button controls in Flex

  1. hello,

    i would like to know if it is possible to change the label with something else than the selected boolean value :
    first click : the label is ‘yes’
    second click : the button is ‘no’
    third click : the label is ‘yes’ etc…

    1. @Adam,

      If you want to display Yes/No instead of true/false, you could do something similar to this:

      <?xml version="1.0" encoding="utf-8"?>
      <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
       
          <mx:Script>
              <![CDATA[
                  protected function setBtnLabel():void {
                      btn.label = yesNoFormatter(btn.selected);
                  }
       
                  protected function yesNoFormatter(value:Boolean):String {
                      return (value) ? "yes" : "no";
                  }
              ]]>
          </mx:Script>
       
          <mx:Button id="btn"
                  toggle="true"
                  selected="true"
                  change="setBtnLabel();"
                  initialize="setBtnLabel();" />
       
      </mx:Application>

      Peter

Comments are closed.