About key listener

Hi,
I’m making my 1st Android app but I meet two problems about keys wich I listen like that :

[lua]local function onKeyEvent(evt)
if evt.phase==“down” and evt.keyName==“back” then
–go back to the menu
end
return true
end

Runtime:addEventListener(“key”,onKeyEvent)[/lua]

  1. When I click on the “back” button of the simulator nothing happen.

  2. When testing on the device, the back button is correclty handled but the volume keys are disabled ! So, I changed “return true” by “return false” and now volume keys are enabled but the back button quit the application (instead of going back to the menu).
    So, what I must return ??

Thanks to help me :slight_smile: [import]uid: 107239 topic_id: 22260 reply_id: 322260[/import]

Hi!

  1. As far as I understand simulator does not support hardware keys.

  2. here the working code for back key:

 local function onKeyEvent( event )  
 local returnValue = true  
  
 if (event.phase=="down" and event.keyName=="back") then  
 -- back to menu  
 end  
  
 return returnValue  
 end  
  
 Runtime:addEventListener( "key", onKeyEvent );   

So… I have one problem with back key and director class :slight_smile:

I have 2 scenes: Scene A and scene B:
Scene A - main scene.
Scene B - sub scene.
In scene B I put this function:

[code] local function onKeyEvent( event )
local returnValue = true

if (event.phase==“down” and event.keyName==“back”) then
Runtime:removeEventListener( “key”, onKeyEvent );
director:changeScene(“menu”, “fade”, 30.0,60.0,90.0)
end

return returnValue
end

Runtime:addEventListener( “key”, onKeyEvent );[/code]

It’s work. But eventListener is not removing, and on scene A when I pressing back key, app change scene to A (again.)

How can I use that function only on scene B? On scene A I want to keep basic function of back key (closing app).

Please help.

[import]uid: 109747 topic_id: 22260 reply_id: 89301[/import]

Thanks but I don’t have problem to handle back key.
What I mean is, if I just handle back key, all other keys lose their default behaviour. If you try your working code, back key will be handled but you won’t be able to increase or decrease the volume directly from the device.
I played many games where they handle back key but I still can change the volume, so how they do ? [import]uid: 107239 topic_id: 22260 reply_id: 89318[/import]

Yes. I have same problem too.
Does anybody knowhs how to use back key in right way? [import]uid: 109747 topic_id: 22260 reply_id: 89503[/import]

I found :))
“return true” must be only for the handled key and not at the end of the listener function. [import]uid: 107239 topic_id: 22260 reply_id: 89973[/import]

Here’s a working example on how to handle the back button: http://developer.anscamobile.com/forum/2012/02/17/disable-android-back-key [import]uid: 117906 topic_id: 22260 reply_id: 113588[/import]