How to control the back button with multiple screens in Libgdx?

If there is a way to control the return button in Libgdx?

for example, in Andengine, I implemented this as follows:

@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { switch (currentScene) { case SPLASH: break; case MENU: Process.killProcess(Process.myPid()); break; case WORLDMENU: start(MENU); break; ... ... } } } 

I have no idea how to do this here, because ApplicationListener only creates, shows, does ... I tried this:

 if (Gdx.input.isButtonPressed(Keys.BACK)){ new ScreenChangeTask(MyScreen.SPLASH); } 

but it still closes my application.

FYI: I have a class Controller extends Game , and I use public void setScreen (Screen screen) to switch between screens.

+6
source share
2 answers

To do this correctly, you need to tell LibGDX to catch the back key:

 Gdx.input.setCatchBackKey(true); 

You should do this somewhere at the beginning of the application. And set it to false when you want the user to be able to use the return key.

+9
source

set

 Gdx.input.setCatchBackKey(true); 

then implement below code on keyUp ...

  @Override public boolean keyUp(int keycode) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { switch (currentScene) { case SPLASH: break; case MENU: Process.killProcess(Process.myPid()); break; case WORLDMENU: game.setScreen(new MenuScreen(game)); //MenuScreen is your class Screen break; return false; } } } 

Hope this helps you

+1
source

All Articles