Event listener to keyboard event not listening in

2019-08-28 09:53发布

问题:

I am doing this inside a module containing viewstacks and their childs. Calling onInit() on creationComplete of module.

When I am inside one of the childs of a viewstack of this module and press Enter, it doesnt not invoke the listener function at all (bp inside this does not get hit).

private function onInit():void{
 this.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
}

private function keyPressed(evt:KeyboardEvent):void
           {//this breakpoint never gets hit on pressing a key in screen
               if (evt.keyCode == Keyboard.ENTER)
               {
                //do this   
                   }               
           }

回答1:

You should add key listeners to stage objects:

private function onInit():void{
    this.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
}


回答2:

This can be very frustrating as there are a few different things that can affect this.

1) Add your event listeners at the appropriate place. The code that you have there is fine for capturing, just ensure it is in the parent or above of where the events are being fired.

2) You need to ensure you have focus. This is usually the issue people run into and it's in the docs but not immediately clear. If you look at the live doc link here and do a search for setFocus() - you'll notice that it is in every one of their examples (except top, which is broken!) - yet, they don't ever mention it in the actual documentation on the page.

http://livedocs.adobe.com/flex/3/html/help.html?content=events_11.html

So, even in their first example, if you click into the app (and not the textbox), it wont work!

<?xml version="1.0"?>
<!-- events/TrapAllKeys.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="initApp();">
<mx:Script><![CDATA[
    private function initApp():void {
        application.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
    }

    private function keyHandler(event:KeyboardEvent):void {
        t1.text = event.keyCode + "/" + event.charCode;
    }
]]></mx:Script>

<mx:TextInput id="myTextInput"/>

<mx:Text id="t1"/>

</mx:Application>

If however, you set focus yourself by changing the init function like this, it will!

private function initApp():void {
        application.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
        myTextInput.setFocus();
    }

Another trick for testing if this is your problem is to add a textbox as a child of the container that has the capturing, if they magically work after you click in that text box - its a focus problem indeed!

=)