Handling Back Key in Libgdx

Zemun This would be a really quick post for handling the back key in android. Back key, if not handled, would mostly exit the application which is its intended purpose but sometimes there is need to give the user a warning popup or maybe goto another screen in the same activity. To achieve this in Libgdx is really simple.

unusually 1st Step: The game class which implements ApplicationListener interface of Libgdx should also be implementing InputProcessor interface. Many functions would get added as a result.

2nd Step: In the create function add these 2 lines.


3rd Step: Implement the event to be executed on tapping the back key.

public boolean keyDown(int keycode) {
      // TODO Auto-generated method stub
       if(keycode == Keys.BACK){
             // Do back button handling (show pause menu?)
             Gdx.app.exit(); //This will exit the app but you can add other options here as well
      return false;

Thats it. Now with different screens we can just check the current screen and then according to it load a different screen or exit the app.

Tagged with: , , , ,

Leave a Reply