Friday, June 15, 2007

How to change focus with the enter key

Here is a simple Flex app that shows how to change the focus of of several textInput components with the enter key. The one thing I have not yet figured out is why, after the Alert window is closed, the focus jumps back to the login button instead of the "fullName" text input field.

enterKeyTest.mxml

<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:local="*">
    <local:focusLoop />
</mx:Application>

focusLoop.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="initApp()">
    <mx:Script>
    <![CDATA[
        ////////////////////////////////////////////////////////////
        import mx.events.CloseEvent;
        import mx.core.UITextField;
        import flash.ui.Keyboard;
        import mx.controls.Alert;
        ////////////////////////////////////////////////////////////
        private function initApp():void
        {
            this.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
        }
        ////////////////////////////////////////////////////////////
        private function keyHandler(event:KeyboardEvent):void
        {
            if(event.keyCode == Keyboard.ENTER)
            {
                if(event.target is UITextField)
                    drawFocus(true);
                else if(event.target.id == "myBtn")
                    showAlert();
            }
        }
        ////////////////////////////////////////////////////////////
         override public function drawFocus(isFocused:Boolean):void
        {
            focusManager.getNextFocusManagerComponent().setFocus();
        ////////////////////////////////////////////////////////////
        }       
        private function showAlert():void
        {
            Alert.show('Clicked Login Button!', '', Alert.OK, this, alertListener);           
            myBtn.focusEnabled=false;
        }
        ////////////////////////////////////////////////////////////
        private function alertListener(eventObj:CloseEvent):void
        {
            fullName.setFocus();
        }   
    ]]>
    </mx:Script>
        <mx:Form>
        <mx:FormItem label="Name">
            <mx:TextInput id="fullName" width="100" focusOut="myBtn.focusEnabled=true"/>
        </mx:FormItem>
        <mx:FormItem label="Street">
            <mx:TextInput width="100" />
        </mx:FormItem>
        <mx:FormItem label="City">
            <mx:TextInput width="100" />
        </mx:FormItem>
        <mx:FormItem label="State">
            <mx:TextInput width="50" maxChars="2" />
        </mx:FormItem>
        <mx:FormItem label="Zip Code">
            <mx:TextInput width="50" maxChars="5" />
        </mx:FormItem>
        <mx:FormItem>
            <mx:Button id="myBtn" label="Login" />
        </mx:FormItem>
    </mx:Form>
</mx:VBox>