Chann Lynn
Chann Lynn

Reputation: 201

Going back to previous state of the same activity

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.

Upvotes: 0

Views: 727

Answers (3)

Michael Yaworski
Michael Yaworski

Reputation: 13483

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
    }
}

Upvotes: 0

Erick Filho
Erick Filho

Reputation: 1962

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!

Upvotes: 1

Jerryl15
Jerryl15

Reputation: 548

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

Upvotes: 1

Related Questions