Creating a toggleable LinkButton control in Flex

The following example shows how you can create a toggleable Flex LinkButton control by extending the mx.skins.halo.LinkButtonSkin and adding custom “selectedUpSkin”, “selectedOverSkin”, “selectedDownSkin”, and “selectedDisabledSkin” skin states.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/09/06/creating-a-toggleable-linkbutton-control-in-flex/ -->
<mx:Application name="LinkButton_toggle_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:ApplicationControlBar dock="true">
        <mx:Form styleName="plain">
            <mx:FormItem label="toggle:">
                <mx:CheckBox id="toggleCheckBox" />
            </mx:FormItem>
            <mx:FormItem label="selected:">
                <mx:CheckBox id="selectedCheckBox"
                        selected="{linkButton.selected}" />
            </mx:FormItem>
        </mx:Form>
    </mx:ApplicationControlBar>

    <mx:LinkButton id="linkButton"
            label="LinkButton"
            toggle="{toggleCheckBox.selected}"
            selected="{selectedCheckBox.selected}"
            skin="skins.ToggleLinkButtonSkin" />

</mx:Application>

skins/ToggleLinkButtonSkin.as

/**
 * http://blog.flexexamples.com/2008/09/06/creating-a-toggleable-linkbutton-control-in-flex/
 */
package {
    import mx.skins.halo.LinkButtonSkin;

    public class ToggleLinkButtonSkin extends LinkButtonSkin {
        public function ToggleLinkButtonSkin() {
            super();
        }

        override protected function updateDisplayList(w:Number, h:Number):void {
            super.updateDisplayList(w, h);

            var cornerRadius:Number = getStyle("cornerRadius");
            var rollOverColor:uint = getStyle("rollOverColor");
            var selectionColor:uint = getStyle("selectionColor");

            graphics.clear();

            switch (name) {
                case "upSkin":
                    // Draw invisible shape so we have a hit area.
                    drawRoundRect(
                        0, 0, w, h, cornerRadius,
                        0, 0);
                    break;


                case "selectedUpSkin":
                case "selectedOverSkin":
                case "overSkin":
                    drawRoundRect(
                        0, 0, w, h, cornerRadius,
                        rollOverColor, 1);
                    break;


                case "selectedDownSkin":
                case "downSkin":
                    drawRoundRect(
                        0, 0, w, h, cornerRadius,
                        selectionColor, 1);
                    break;


                case "selectedDisabledSkin":
                case "disabledSkin":
                    // Draw invisible shape so we have a hit area.
                    drawRoundRect(
                        0, 0, w, h, cornerRadius,
                        0, 0);
                    break;
            }
        }
    }
}

View source is enabled in the following example.

You can also set the LinkButton control’s skin style in an external .CSS file or <mx:Style /> block, as seen in the following example:

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/09/06/creating-a-toggleable-linkbutton-control-in-flex/ -->
<mx:Application name="LinkButton_toggle_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Style>
        LinkButton {
            skin: ClassReference("skins.ToggleLinkButtonSkin");
        }
    </mx:Style>

    <mx:ApplicationControlBar dock="true">
        <mx:Form styleName="plain">
            <mx:FormItem label="toggle:">
                <mx:CheckBox id="toggleCheckBox" />
            </mx:FormItem>
            <mx:FormItem label="selected:">
                <mx:CheckBox id="selectedCheckBox"
                        selected="{linkButton.selected}" />
            </mx:FormItem>
        </mx:Form>
    </mx:ApplicationControlBar>

    <mx:LinkButton id="linkButton"
            label="LinkButton"
            toggle="{toggleCheckBox.selected}"
            selected="{selectedCheckBox.selected}" />

</mx:Application>

Or, you can set the skin style using ActionScript, as seen in the following example:

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/09/06/creating-a-toggleable-linkbutton-control-in-flex/ -->
<mx:Application name="LinkButton_toggle_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import skins.ToggleLinkButtonSkin;

            private function init():void {
                linkButton.setStyle("skin", ToggleLinkButtonSkin);
            }
        ]]>
    </mx:Script>

    <mx:ApplicationControlBar dock="true">
        <mx:Form styleName="plain">
            <mx:FormItem label="toggle:">
                <mx:CheckBox id="toggleCheckBox" />
            </mx:FormItem>
            <mx:FormItem label="selected:">
                <mx:CheckBox id="selectedCheckBox"
                        selected="{linkButton.selected}" />
            </mx:FormItem>
        </mx:Form>
    </mx:ApplicationControlBar>

    <mx:LinkButton id="linkButton"
            label="LinkButton"
            toggle="{toggleCheckBox.selected}"
            selected="{selectedCheckBox.selected}"
            initialize="init();" />

</mx:Application>

Due to popular demand, here is the “same” example in a more ActionScript friendly format:

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/09/06/creating-a-toggleable-linkbutton-control-in-flex/ -->
<mx:Application name="LinkButton_toggle_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        initialize="init();">

    <mx:Script>
        <![CDATA[
            import skins.ToggleLinkButtonSkin;

            import mx.containers.ApplicationControlBar;
            import mx.containers.Form;
            import mx.containers.FormItem;
            import mx.controls.CheckBox;
            import mx.controls.LinkButton;

            private var toggleCheckBox:CheckBox;
            private var selectedCheckBox:CheckBox;
            private var linkButton:LinkButton;

            private function init():void {
                toggleCheckBox = new CheckBox();
                toggleCheckBox.addEventListener(Event.CHANGE,
                            toggleCheckBox_change);

                selectedCheckBox = new CheckBox();
                selectedCheckBox.addEventListener(Event.CHANGE,
                            selectedCheckBox_change);

                var formItem1:FormItem = new FormItem();
                formItem1.label = "toggle:";
                formItem1.addChild(toggleCheckBox);

                var formItem2:FormItem = new FormItem();
                formItem2.label = "selected:";
                formItem2.addChild(selectedCheckBox);

                var form:Form = new Form();
                form.styleName = "plain";
                form.addChild(formItem1);
                form.addChild(formItem2);

                var appControlBar:ApplicationControlBar;
                appControlBar = new ApplicationControlBar();
                appControlBar.dock = true;
                appControlBar.addChild(form);
                addChildAt(appControlBar, 0);

                linkButton = new LinkButton();
                linkButton.label = "LinkButton";
                linkButton.setStyle("skin", ToggleLinkButtonSkin);
                linkButton.addEventListener(Event.CHANGE,
                            linkButton_change);
                addChild(linkButton);
            }

            private function toggleCheckBox_change(evt:Event):void {
                linkButton.toggle = toggleCheckBox.selected;
            }

            private function selectedCheckBox_change(evt:Event):void {
                linkButton.selected = selectedCheckBox.selected;
            }

            private function linkButton_change(evt:Event):void {
                selectedCheckBox.selected = linkButton.selected;
            }
        ]]>
    </mx:Script>

</mx:Application>

8 thoughts on “Creating a toggleable LinkButton control in Flex

  1. @xiangjiazhao : first click the button. Nothing happens. Then check “Toggle” and click the button again. You see the difference ? The button now behaves like a checkbox.

  2. How would I go about using this in a way that would allow me to control the color of the LinkButton? Do I need to create a separate ToggleLinkButtonSkin class for each color I intend to use?

  3. Dave,

    I believe the example above uses the existing selectionColor for the “selectedDownSkin” state. If you wanted to use a separate color, you could probably get away with extending the LinkButton control, add metadata for a new “selectedToggleStyle” style and use that color in your custom ToggleLinkButtonSkin skin instead.

    I can try taking a look at it again tonight and see if I can create a new example.

    Peter

  4. I’ll answer my own question. I was able to access the LinkButton that was calling the ToggleLinkButtonSkin class by casting the parent as a LinkButton:

    var lbtn_ref:LinkButton = (LinkButton)(this.parent);

    From there, I could determine what color I wanted to style the button based on the button’s label.

  5. What a weird issue to run into but I did.

    So, yesterday I was tasked with building a charting app (simple 1 chart based on XML with a refresh interval). No problem…jumped in Flex Builder and banged it out in roughly 20 minutes (not bragging; will explain the reference in a few). The app worked perfectly fine.

    Today I was tasked with integrating it into the actual page and putting up a test version to look at. So I did, showed Dave M. (he assigned it to me) but he was busy so I showed my manager, and it didn’t work!!! Huh?

    First Error
    My manager hit an RSL problem. The issue was with the mime type not being registered in Apache. Easy one to get beyond. I nix’ed the use of RSL for now, until Apache on this server gets updated, and moved one.

    Second Error
    The code uses a URLLoader to load the XML. I added a listener for HTTPStatusEvent.HTTP_STATUS. 403 and 401 are there for authentication purposes and 200 is the only other I coded. Everything works great. If I get a 200 the timer is stopped then started again. I also have an Event.COMPLETE to “parse” the data and throw it in my chart (which charting+xml is saweet!!!). Again…everything works great. I sent it to my manager…BROKEN! Ahh…only in Firefox though. Huh? How’s that? This is Flash for Christ’s sake!!

    I remove my setInterval and replace it with a Timer. That doesn’t work. I tried numerous other fixes and none of those worked. Then I added a double click listener to the chart and had it call loadData which actually worked. So I knew the networking portion was fine. Why in the world is my switch statement not making it to case 200:?

    To find out I threw in an Alert.show(event.status) to see what code was coming back. It was 0!!!! HOW? HUH? WHAT?

    Last year I learned a new acronym from Sarge. We were working on something and the issue I was having was a result of RTFM. RTFM (to me) reads “Read The Freaking Manual” (substitute your own F* word at your leisure). :-)

    That was the problem…RTFM:
    bq. “HTTPStatusEvent objects are always sent before error or completion events. An HTTPStatusEvent object does not necessarily indicate an error condition; it simply reflects the HTTP status code (if any) that is provided by the networking stack. Some Flash Player environments may be unable to detect HTTP status codes; a status code of 0 is always reported in these cases.”

Comments are closed.