Search code examples
apache-flexfocussetfocus

How to programmatically set focus to HorizontalList so that it could receive key events (Flex)?


Please, look at the code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:creationComplete>
    <![CDATA[
        list.setFocus();
    ]]>
</mx:creationComplete>
<mx:HorizontalList id="list">
    <mx:creationComplete>
        <![CDATA[
            setFocus();
        ]]>
    </mx:creationComplete>
    <mx:focusIn>
        <![CDATA[
            trace("Received focus");
        ]]>
    </mx:focusIn>
    <mx:keyDown>
        <![CDATA[
            trace("Key down");
        ]]>
    </mx:keyDown>
    <mx:dataProvider>
        <mx:Object label="Some"/>
        <mx:Object label="Different"/>
        <mx:Object label="Stuff"/>
    </mx:dataProvider>
</mx:HorizontalList>

As you see, I try to make my HorizontalList focused when application is loaded. And I actually receive Received focus message in console. But I expected that I would be able to navigate over list elements with arrow keys after setting focus. But that's not the case. They work only after clicking component with mouse. So, what am I doing wrong? How to make list have focus and respond to arrow keys?


Solution

  • Is your app running inside a browser? You may have to set focus on the SWF object (via JavaScript) in order to begin interacting with it without clicking the object first.

    For example, assuming you're using Flex Builder, try adding a line like this one to the end of the SCRIPT tag of your index.template.html file:

    window.onload = function()
    {
        document.getElementById("${application}").focus();
    };
    

    You may need to do a little tweaking depending on your specific situation, but that's probably the issue. Setting focus on the Flash object explicitly should do the trick. Hope it helps!