Search code examples
androidlibgdx

libgdx-android: Intercepting back key and confirm exit


Using libgdx, how can I intercept the android BACK key in order to do some preprocessing (e.g. asking for confirmation from user), before actually performing the command to exit the game?


Solution

  • 1. Enable catching of Back Key.

    In the class that implements ApplicationListener

       @Override
       public void create() {
            ...
            Gdx.input.setCatchBackKey(true);
            ...
       }
    

    2. Handle catching of Back Key.

    In a class that implements the InputProcessor

       @Override
       public boolean keyDown(int keycode) {
            ...
            if(keycode == Keys.BACK){
               // Optional back button handling (e.g. ask for confirmation)
               ...
               if (shouldReallyQuit)
                 Gdx.app.exit();
            }
            return false;
       }