Peter Hall's Flash, Flex and AIR blog. News and insights into development with Flash, Flex and AIR.

This page is powered by Blogger. Isn't yours?
Tuesday, July 24, 2007

How to really hide a component in Flex

Ok, so it sounds obvious: myComponent.visible = false;. But actually this doesn't do everything you might want it to. If the parent is a VBox or an HBox then there will be a gap, where the component should be. You can set its height to zero, but then there is still the verticalGap or horizontalGap to worry about.

You can get around that still, by using getStyle and subtracting the gap. But this is starting to get ugly. Another options is to remove the child altogether, which is fine in many circumstances, but can get screwed up if other children are being added and removed.

The solution I found is to use the includeInLayout property, in combination with visible. Setting includeInLayout to false means that the layout engine will not leave gaps or spaces around the component, but it will still be drawn if you don't set visible to false too. Here's an example with states:

<?xml version="1.0" encoding="utf-8"?> 
<mx:Application 
     xmlns:mx="http://www.adobe.com/2006/mxml" 
     layout="vertical">
 
     <mx:states> 
          <mx:State name="hideText"> 
          <mx:SetProperty target="{myText}" 
          name="includeInLayout" value="false" /> 
               <mx:SetProperty target="{myText}" 
                    name="visible" value="false" /> 
          </mx:State>
     </mx:states>
      
      
     <mx:Button label="hide text" 
          click="currentState = 'hideText'" />
     <mx:Text id="myText" text="hello, this text will 
     be hidden or shown, depending on the buttons" />
     <mx:Button label="show text" 
          click="currentState = ''" />
</mx:Application>

Easy!

Btw if you are wondering why I'm not blogging much these days, I've been working on building a development company in UK and South Africa. Memorphic has been growing nicely over the last year, in numbers and in the skills of our developers. So, let's just say I've been busy!