Flex Demo 5 - View Stack and Handling Keystrokes

View Flex Demo 5

This demo addresses using a ViewStack and handling keystrokes. In this case, we handle keystrokes on a application-wide basis. A component class, 'Screen1.mxml', is a Spark Group container with three simple labels:
    <s:Label text="THIS IS SCREEN 1" y="10" x="10" fontSize="30"/> 
    <s:Label y="84" text="Press '2' for screen 2" x="9" fontSize="16"/> 
    <s:Label y="110" text="Press '3' for screen 3" x="10" fontSize="16"/> 
Two other component classes for Screen 2 and Screen 3 look very similar.

The main class for the application holds a ViewStack that contains all the application states:
    <mx:ViewStack id="screens"> 
        <s:NavigatorContent id="screen1"> 
            <components:Screen1/> 
        </s:NavigatorContent> 
        <s:NavigatorContent id="screen2"> 
            <components:Screen2/> 
        </s:NavigatorContent> 
        <s:NavigatorContent id="screen3"> 
            <components:Screen3/> 
        </s:NavigatorContent> 
    </mx:ViewStack> 
Here is the bit of code that runs once the application has initiated:
            protected function application1_applicationCompleteHandler(event:FlexEvent):void 
            { 
                screens.selectedIndex=0;
                stage.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
                stage.focus = this;
            } 
This sets the initial screen and initializes the keyboard listener.

The actual keyboard handler and its supporting methods are shown here:
            protected function keyHandler(event:KeyboardEvent):void { 
                if (event.charCode == 49) { 
                    toScreen1();
                } else if (event.charCode == 50) { 
                    toScreen2();
                } else if (event.charCode == 51) { 
                    toScreen3();
                } 
            } 
            
            protected function toScreen1():void { 
                screens.selectedIndex=0;
            } 
            
            protected function toScreen2():void { 
                screens.selectedIndex=1;
            } 
            
            protected function toScreen3():void { 
                screens.selectedIndex=2;
            }