0

I would like to get back to previous state of an activity when I press back button. I mean I'm now in activity_B and I would like to go back to the previous state of activity_B. Is it possible? If so, please explain how.

Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
Chann Lynn
  • 201
  • 1
  • 3
  • 14
  • 2
    Can you specify clearly What is the problem? You Navigate from ActivityA to B?. What do you mean by previous state. WHen you press back button activity is popped from back stack destoryed and previous activity in backstack takes focus – Raghunandan Jan 12 '14 at 04:52
  • Sorry for that , what I means really is I'm now in activity_B and I would like to go back to the previous stage of activity_B (The same activity but previous stage) . – Chann Lynn Jan 12 '14 at 04:56
  • 1
    Then how do you get back to activity A after you're in the previous state of activity B? – Michael Yaworski Jan 12 '14 at 05:06
  • There's no activity_A . I am in activity_B and I would like to go back to previous stage of activity_B . That's all . About activity_A is that I just tried to explain . Sorry for confusing you . – Chann Lynn Jan 12 '14 at 05:09
  • @ChannLynn what previous state also back button is meant to take you back to previous activity in the back stack. – Raghunandan Jan 12 '14 at 05:11

3 Answers3

1

You can override onBackPressed() method, like this:

@Override
public void onBackPressed() {
   // Your code
}

Make sure not to call super.

In general, I would advise against that because it breaks the UX. The user expects the back button to kill the entire window and it is not going to happen. Think about it!

Hope this helps!

Erick Filho
  • 1,962
  • 3
  • 18
  • 31
1

Not sure what you're trying to ask, but I think its this:

@Override
public void onBackPressed() {
//Code to go back to previous state of activity b.
}

and if you are using API<5

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // your code
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

Re:How to handle back button in activity

Community
  • 1
  • 1
Jerryl15
  • 548
  • 3
  • 10
  • backbutton is meant to navigate to previous activity. I would not override the functionality unless it is really necessary. – Raghunandan Jan 12 '14 at 05:09
0

This is what I'm assuming your hierarchy is:

In activity B, if you press back, it should go restore the previous "state" of activity B. Once the the previous state, the back button should bring you back to activity A.

With that, I suggest adding the onBackPressed method to your activity B:

public void onBackPressed()
{
    // check if in the second state of activity B
    {
        // restore previous state of activity B
    }
    else { // already in the previous state of activity B
        finish(); // go back to activity A
    }
}
Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97