Search code examples
androidcocos2d-xcocos2d-x-3.0android-event

Listen Android back button in cocos2d-x


I want to track android back button in android activity.

I have all ready work on back button in onKeyReleased() in C++ , but when I check back button in activity methods like onBackPressed() , onKeyUp() , OnKeyDown() e.t.c then I get nothing.

Please help me with the same.


Solution

  • Well you have to create a new event listener for the keyboard in the init of your class. Because I don't know what you have at this moment, this is how I implement the back button listener for Android:

    bool YourScene::init()
    {
        if(!Layer::init()) return false;
        auto listener = EventListenerKeyboard::create();
        listener->onKeyReleased = CC_CALLBACK_2(YourScene::onKeyReleased, this);
        Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
        ...........
    }
    
    void YourScene::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event)
    {
        if(keyCode == EventKeyboard::KeyCode::KEY_BACK)
        {
            // IMPLEMENT YOUR BACK BUTTON LOGIN HERE
        }
    }