Qianqian
Qianqian

Reputation: 2124

cocos2dx onKeyReleased gets called at keydown instead of keyup in android

I am recently working with cocos2dx 3.0rc2 and I want to respond the back key event in android platform. I learned that I could override the onKeyReleased method of the layer and setKeypadEnabled(true) to capture the back key.

However I got a problem, I can capture the event, but not accurately. That is, I expect this method gets called when I released my finger from the back key. However it now gets triggered as soon as I put my finger on the back key. That being said, it responds at key-down phase while I wish it could do it at key-up phase.

Can you help me with this? By the way, I tested the code and it seemed that on win32, the backspace key was not responded (But it does not matter for me as I only care about android)

Here are the code blocks:

init:

...
this->setKeypadEnabled(true);
...

onKeyReleased:

...
if(keyCode ==  EventKeyboard::KeyCode::KEY_BACKSPACE) {
    onBack(nullptr);
}
...

I also tried the other way to capture the event, by setting the listener instead of simply putting setKeypadEnabled(true). The result is the same.

I appreciate your help!

Upvotes: 0

Views: 1327

Answers (3)

joiyao
joiyao

Reputation: 11

In our apps, we did like this:

auto obKeyBackListener = EventListenerKeyboard::create();
obKeyBackListener->onKeyReleased = [=](EventKeyboard::KeyCode keyCode, Event* event)
{
    if (keyCode == EventKeyboard::KeyCode::KEY_BACK) // KEY_BACK
    {
        event->stopPropagation(); // stop propagation for this event
        onBack(nullptr);        
    }
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(obKeyBackListener, this);

Upvotes: 1

w770115
w770115

Reputation: 187

Change this:

this->setKeypadEnabled(true);

with this:

auto keyboardListener = EventListenerKeyboard::create();
keyboardListener->onKeyReleased = CC_CALLBACK_2(HelloWorld::onKeyReleased, this);
this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(keyboardListener, this);

Upvotes: 0

Abdul
Abdul

Reputation: 44

You have written the correct code but have used the wrong key code.

It shoud be EventKeyboard::KeyCode::KEY_ESCAPE.

Upvotes: 0

Related Questions