Monday, April 23, 2012

Override the Device's Back button

When browsing a game's Options Menu and decided to not modify the current settings,  you simply want to use your phone's Back button as, well, for going back to Main Menu.

But sadly, this is not the default behavior of that Back button.  When you try to create your game, pressing that button will quit (umm... hide, rather) your app.

But don't lose hope.  There's actually a way of changing that default behavior.

On your app's Activity class, add the following snippet.

@override
public void onBackPressed() {
   if (state == STATE_MAINMENU) {
      super.onBackPressed();
   } else {

      //do something else
   }
}


Of course, both state and STATE_MAINMENU has to be defined for the snippet to be usable.  Also, whatever new behavior you want the Back button will have to do will be coded on the else part of the snippet, as indicated by do something else.

(via Creek Codes)

1 comment:

  1. Amazing blog and very interesting stuff you got here! I definitely learned a lot from reading through some of your earlier posts as well and decided to drop a comment on this one!

    ReplyDelete