Using the back button on Android with Cocos2d-x 3

Among the many changes done in version 3 of cocos2d-x CCLayer::backKeyClicked() has been deprecated. So how do you catch that back key click these day?
Here’s how, you need to override Layer::onKeyReleased() and compare the value of keyCode to KEY_ESCAPE, as shown in the following code

void MyLayer::onKeyReleased(EventKeyboard::KeyCode keyCode, Event *event) {
	if(keyCode == EventKeyboard::KeyCode::KEY_ESCAPE) {
		/*
			Handle the back click
		*/
	}
}

From there you just need to handle the click.
You will also need to enable the Keypad, otherwise the layer will not get notifications on such interactions.
You do that using Layer::setKeyboardEnabled(), set it to true in your Layer’s init() function.
In versions of cocos2d-x 3 prior to v3.3 you would use Layer::setKeypadEnabled() instead, which has been deprecated in later versions.

8 thoughts on “Using the back button on Android with Cocos2d-x 3”

  1. Hi, Thanks it did work..
    But it says setKeypadEnabled() is also deprecated in V-3.3, but i couldn’t find its alternative. Can you help please?

  2. I have tried “setKeyboardEnabled(true)”, also but in either case it says:
    warning: ‘virtual void cocos2d::Layer::setKeyboardEnabled(bool)’ is deprecated (declared at jni/../../cocos2d/cocos/3d/../2d/CCLayer.h:139) [-Wdeprecated-declarations]

  3. According to the deprecated functions list of cocos2d-x 3.3 setKeyboardEnabled () is not deprecated.
    Are you sure you are working with the correct API?

  4. Yes that’s the reason i posted the question here…I also found it on there list to be valid..but compiler says its deprecated.
    Yes m sure its v-3.3, and by the way how could I use version newer then v-3.3 before its release?

    1. I have the same problem with v-3.3.
      compiler says its deprecated .
      in CCLayer.h line 154 you can find

      CC_DEPRECATED_ATTRIBUTE virtual void setKeypadEnabled(bool value);

  5. Indeed, the compiler says that “setKeyboardEnabled()” is deprecated.

    Since Cocos2d-X V3, there is a new mechanism to catch user events (like the “back button pressed” event ). It’s called EventDispatcher Mechanism, see: http://www.cocos2d-x.org/wiki/EventDispatcher_Mechanism

    I’ve registered the keyboard events with the following snippet code:

    auto listener = EventListenerKeyboard::create();
    listener->onKeyReleased = CC_CALLBACK_2(MainScene::onKeyReleased, this);

    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);

    And I’ve used the same function “onKeyReleased” shown on this post, and it works! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *