Toggling buttons in a ToggleButtonBar control in Flex

The following example shows how you can toggle buttons in a Flex ToggleButtonBar control by setting the Boolean toggleOnClick property.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2009/01/21/toggling-buttons-in-a-togglebuttonbar-control-in-flex/ -->
<mx:Application name="ToggleButtonBar_toggleOnClick_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="top"
        backgroundColor="white">

    <mx:ApplicationControlBar dock="true">
        <mx:Form styleName="plain">
            <mx:FormItem label="toggleOnClick:">
                <mx:CheckBox id="checkBox" />
            </mx:FormItem>
            <mx:FormItem label="selectedIndex:">
                <mx:Label text="{toggleButtonBar.selectedIndex}" />
            </mx:FormItem>
        </mx:Form>
    </mx:ApplicationControlBar>

    <mx:ToggleButtonBar id="toggleButtonBar"
            toggleOnClick="{checkBox.selected}"
            dataProvider="{viewStack}" />

    <mx:ViewStack id="viewStack"
            width="100%"
            height="100%">
        <mx:VBox label="Red" backgroundColor="red" />
        <mx:VBox label="Orange" backgroundColor="haloOrange" />
        <mx:VBox label="Yellow" backgroundColor="yellow" />
        <mx:VBox label="Green" backgroundColor="haloGreen" />
        <mx:VBox label="Blue" backgroundColor="haloBlue" />
    </mx:ViewStack>

    <mx:Label text="{Capabilities.version}" />

</mx:Application>

View source is enabled in the following example.

4 thoughts on “Toggling buttons in a ToggleButtonBar control in Flex

  1. I’m not sure that I see any difference between when the checkBox is selected or not. What should I be seeing?

  2. Wow, I really should go back and add SWFs to these older posts.

    Eric,
    When the toggleOnClick CheckBox is deselected, clicking an already selected button has no effect and the selectedIndex doesn’t change. When the toggleOnClick CheckBox is selected, clicking an already selected button sets the selectedIndex property to -1.

    I’ll try and get that SWF up right now…

    Peter

  3. It seems to be a bug, when you set your ToggleButtonBar’s selectedIndex to -1 within the ToggleButtonBar tag it will register as 0 when you run the app. I found a fix:

    When you initialize your app, run a method with the following actionScript:

    this.toggleButtonBar.selectedIndex = -1;

    That will deselect the button. You can take it one step further and hide your viewStack by making it visible ONLY when this.toggleButtonBar.selectedIndex != -1 by adding it to the viewStack tag:

    mx:ViewStack id=”viewStack” visible=”{this.toggleButton.selectedIndex != -1}”

    Hope that helps.

Comments are closed.