Adobe Flex – Controlling focus with ActionScript

For my up and coming project, very soon to be released, I’ve been using the client side Flash based technology Adobe Flex. The best way to describe Flex is probably Flash for programmers. It gives the programmer complete control over the application, using XML to define components and embedded ActionScript to specify the more complex interactions between them. It’s a fantastic technology, produces very slick interfaces very fast and best of all, is totally free. Well, free if you’re happy using the command line SDK to compile, otherwise their IDE is only about £150.

Having said all that, there are a couple of things that you think should be easy, and turn out not to be so obvious. This is particularly true when you want to tweak the built in UI functionality to do something different. The Flex developers have generally done a great job, but some of the form and error handling is not quite ideal and needs some tweaks to really work well.

The application I’m writing has lots of text boxes in a vertical column to fill in, one after the other. Straight out of the box the tab order works sensibly which is great, but I had a lot of feedback requesting that pressing enter should advance the form to the next field. Fortunately text fields have an “enter” event defined so I thought I could be clever and put something like:

    <mx:TextInput enter="focusOut" />

since focusOut is another event associated with TextInputs. I suppose practically speaking I shouldn’t expect that to work, but I thought there must be a built in function I could call on pressing enter to advance the form focus. Anyway, either there isn’t one or I couldn’t find it, so instead I defined a method called nextElement which will programmatically find the next component and set the focus on it, as so:

<mx:Script>
    <![CDATA[
        import mx.managers.IFocusManagerComponent;

        public function nextElement():void
        {
            var nextComponent:IFocusManagerComponent = focusManager.getNextFocusManagerComponent(true);
            nextComponent.setFocus();
        }
    ]]>

</mx:Script>

<mx:TextInput enter="nextElement()" />

The code should be pretty straight forward, the method simply finds the next component using the focusManager and sets the focus on that. Easy when you know how.

Leave a Reply

Your email address will not be published. Required fields are marked *