-1

I have an application that when a button is clicked it changes the content view, but when I press the back button, it closes the activity. How do I change what the back button does. In this case it will be the back button changing the layout again.

Thanks

cnfw
  • 770
  • 2
  • 11
  • 28

4 Answers4

8

You must override onBackPressed() in your activity.

@Override
public void onBackPressed() {
    //your code when back button pressed
}

The onBackPressed method is called when the back Button is pressed, for that, you must change the content of this method by overriding it.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Nermeen
  • 15,883
  • 5
  • 59
  • 72
3

Solved here: Override back button to act like home button

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        //Do what you want here
        moveTaskToBack(true);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
Community
  • 1
  • 1
RobGThai
  • 5,937
  • 8
  • 41
  • 59
2

You can override onBackpressed:

@Override
public void onBackPressed() {
    // Do your stuff....
}
Iñigo
  • 12,723
  • 2
  • 31
  • 31
0

The new recommended way is to use OnBackPressedCallback API, which is more flexible than old onBackPressed() method and may be used not only from Activity or Fragment

See more details in the official guide and API reference

gildor
  • 1,789
  • 14
  • 19