Click to Close Accordion

It seems odd that all my Flex posting here is about how to make a built in component do something it wasnt intended to do.  This time, I had clients which wanted an Accordion header to close, if clicked when it was already open.  I’m not particularly fond of the interaction, as I fear it’ll confuse users, but a job is a job, and if thats really what they want, then I needed to find a way to do it.

This was actually surprisingly easy.  All I needed to do was subclass Accordion, and override the behavior of the "headerPress" method.   Heres what I ended up with:

import mx.controls.SimpleButton;
import mx.core.View;
class custom.ClickToCloseAccordion extends mx.containers.Accordion{
    private var __headerClass:Function ;
    function headerPress(header:SimpleButton):Void {
      // method to allow headers to be clicked for open or close.
     var prevValue:Number = selectedIndex;
      if (getHeaderAt(prevValue) != header){
        // content_mc is placed onto the button so we have to access it via []
        selectedChild = header["content_mc"];
        // break out of function;
        return;
      } else if(selectedIndex > 0){
        var indexToTry = selectedIndex -1;
        selectedIndex = indexToTry;
      }
    }
}

So, whats happening is that each time the AccordionHeader is clicked, I check to see if the clicked header is the currently open one (getHeaderAt(selectedIndex)) will return the currently selected header.  If the clicked header is not the currently open one, I set the selected child to the selected header,

selectedChild = header["content_mc"];

If it is, I set the selectedIndex to one less than the currently selected index.

To test, I put the class above in a subdir called "custom" and ran this MXML:

<?xml version="1.0" encoding="iso-8859-1"?>
<mx:Application
 width="800" height="600"
 xmlns:mx="
http://www.macromedia.com/2003/mxml
 xmlns:c="custom.*">
 <c:ClickToCloseAccordion id="myAcc" width="100%" height="80%">
  <mx:HBox label="Item 1" width="100%" height="100%"/>
  <mx:VBox label="Item 2" width="100%" height="100%"/>
  <mx:HBox label="Item 3" width="100%" height="100%"/>
 </c:ClickToCloseAccordion> 
 
</mx:Application>

Have fun!

There are no comments.

Leave a Reply