Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage back button with multiple screens in Libgdx?

Tags:

java

back

libgdx

If there is some way how to manage back button in Libgdx?

for example in Andengine I have implemented this like that:

@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 don't have idea how to do it here, because ApplicationListener has only create, show, render... I tryed this:

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

but it still closes my application.

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

like image 792
Aleksandrs Avatar asked Mar 14 '13 20:03

Aleksandrs


2 Answers

In order to do this properly you need to tell LibGDX to catch the back key:

Gdx.input.setCatchBackKey(true);

You should do this somewhere early in the application. And set it to false when you want the user to be able to use the back key.

like image 68
Jyro117 Avatar answered Sep 21 '22 10:09

Jyro117


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 will help you

like image 41
Muhammad Aamir Ali Avatar answered Sep 22 '22 10:09

Muhammad Aamir Ali