We're working on some projects in Flex where the use of the keyboard to navigate through the application is a key aspect.
They're both Flex 2 form based application
Our goals were :
- at the start up of the application give the focus to the first form field
- pressing the tab key cycling the focus through all the form fields
Although it seams like very simple, the focus in Flex 2 is not so easy.
We had strange behaviour that mostly depend on how the Internet Explorer uses the ActiveX contents :
- although when the application has been loaded the foucs was on the first field, pressing the tab key once, the focus goes outside the Flash Player applet to the browser controls
To solve the problem of the fucus lost by the Flash Player you can use this small workaround :
keyFocusChange="event.preventDefault();focusManager.getNextFocusManagerComponent(event.shiftKey).setFocus()"
The keyFocusChange is on the Application tag.
In order to make the focus in Flex 2 works for Internet Explorer, it's not enough to set it up using Javascript when the page loads.
Internet Explorer does not give you the ability to an ActiveX content to get the focus.
So for example in a Flex 2 application that has 3 text inputs when the last one has the focus and you click on the tab, the focus quits from the Flash Player 9 ActiveX and goes to the HTML page content.
That's a bad behavior for your application.
To overcome this problem we have to intercept the key pressed by the user and disable the default action of the browser to prevent the browser handling of the key.
Once the TAB key has been intercepted we have to communicate it to the application adding a javascript callback.
this Javascript function calls an Actionscript function with the :
ExternalInterface.addCallback("javascriptFunct", "actionscriptFunc")
Now what we have to do is using the focusManager.getNextFocusManagerComponent() in the Actionscript function.
Add this Javascript functions to the HTML wrapper to use when compile the Flex application :
On the Flex side :
import mx.controls.Alert;
import mx.events.FlexEvent;
private function init(e:FlexEvent):void {
// force the focus to the first text input
input1.setFocus();
// add the callback of the javascript function actionScriptFunction
ExternalInterface.addCallback("actionScriptFunction", callMe);
}
private function callMe(name:String):void
{
if (name == "false") {
// only the TAB key has been pressed
focusManager.getNextFocusManagerComponent().setFocus();
} else {
// the combination of SHIFT+TAB has been pressed
focusManager.getNextFocusManagerComponent(true).setFocus();
}
}
]]>