I want to switch between views in a ViewStack or TabNavigator control but I don't like to use index values to identify the views. Index values might change if I rearrange the order of the views, and they are hard to remember.
Switching views based on the component id is easier and less error-prone. It lets other code or components request view changes without having to change the ViewStack's index property directly.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical" >
<mx:Script>
<![CDATA[
import mx.core.Container;
import mx.events.IndexChangedEvent;
/**
* Looks through the views in the stack to find one whose id matches,
* then switches to it. This will fire the the ViewStack's change event.
*/
public function switchView(viewId:String):void
{
var container:Container = Container(nav.getChildByName(viewId));
if (container != null)
{
nav.selectedChild = container;
}
}
/**
* Called when the selected component in the ViewStack changes.
*/
public function onViewChange(evt:IndexChangedEvent):void
{
var panel:Panel = nav.getChildAt(evt.newIndex) as Panel;
panel.title = panel.id + " selected.";
}
]]>
</mx:Script>
<mx:HBox width="100%">
<mx:Button id="btn1" width="150" label="switchView('panel1')" click="switchView('panel1');" />
<mx:Button id="btn2" width="150" label="switchView('panel2')" click="switchView('panel2');" />
<mx:Button id="btn3" width="150" label="switchView('panel3')" click="switchView('panel3');" />
</mx:HBox>
<mx:ViewStack id="nav" width="100%" height="100%" change="onViewChange(event)">
<mx:Panel id="panel1" label="Panel One" width="100%" height="100%" backgroundColor="#CCCCEE" />
<mx:Panel id="panel2" label="Panel Two" width="100%" height="100%" backgroundColor="#EECCCC" />
<mx:Panel id="panel3" label="Panel Three" width="100%" height="100%" backgroundColor="#CCEECC" />
</mx:ViewStack>
</mx:Application>
Click any of the buttons to switch views based on the component id. You can switch views from anywhere else in your scripts just by calling switchView('viewId').
This example also shows how to call a common method when the view is switched, using the change property of the ViewStack to specify the onViewChange() method to be called when the CHANGE event is fired. In the onViewChange() method, it gets a reference to the newly-displayed container using the getChildAt() method and the newIndex property of the event.