If one or more view states apply to a single component or set of components, you define a custom component that comprises this component or components, and specify the view states in the component definition, rather than at the Application tag level. For example, if a view state adds a Button control to an HBox container, consider making the HBox a custom component and defining a state in the component that adds the button. You should consider doing this particularly if you have multiple states that do nothing but modify the HBox container.
Similarly, if a custom component has multiple view states, define the view states in the component code, not in the main application. For example, if a custom TitleWindow component has a collapsed view state and a expanded view state, you should define these view states in the panel MXML component, not in the main application file.
This way, you segregate the view state definitions into the specific components to which they apply. An item renderer is one example of good use of a multiple view state MXML component.
The following example shows a custom component for a TitleWindow component that has two view states, collapsed and expanded:
<?xml version="1.0"?>
<mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml"
close="checkCollapse();" headerHeight="40" showCloseButton="true">
<mx:Script>
<![CDATA[
// Skins for the close button when the
// TitleWindow container is collapsed.
[Embed(source="closeButtonUpSkin.jpg")]
[Bindable]
public var closeBUp:Class;
[Embed(source="closeButtonDownSkin.jpg")]
[Bindable]
public var closeBDown:Class;
[Embed(source="closeButtonOverSkin.jpg")]
[Bindable]
public var closeBOver:Class;
private function checkCollapse():void {
currentState =
currentState == "collapsed" ? "" : "collapsed";
}
]]>
</mx:Script>
<mx:states>
<mx:State name="collapsed">
<mx:SetProperty
name="height"
value="{getStyle('headerHeight')}"/>
<mx:SetStyle
name="closeButtonUpSkin"
value="{closeBUp}"/>
<mx:SetStyle
name="closeButtonDownSkin"
value="{closeBDown}"/>
<mx:SetStyle
name="closeButtonOverSkin"
value="{closeBOver}"/>
</mx:State>
</mx:states>
</mx:TitleWindow>
This example replaces the default close icon for a TitleWindow when the component is in the collapsed state.
You can then use this component in an application, as the following example shows:
<?xml version="1.0"?>
<!-- states\StatesTitleWindowMain.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:MyComp="myComponents.*">
<MyComp:StateTitleWindow id="myP" title="My Application">
<mx:HBox width="100%">
<mx:Button label="Click Me"/>
<mx:TextArea/>
</mx:HBox>
<mx:ControlBar width="100%">
<mx:Label text="Quantity"/>
<mx:NumericStepper/>
<!-- Use Spacer to push Button control to the right. -->
<mx:Spacer width="100%"/>
<mx:Button label="Add to Cart"/>
</mx:ControlBar>
</MyComp:StateTitleWindow>
</mx:Application>
The executing SWF file for the previous example is shown below: