Search code examples
androidandroid-studioandroid-activityandroid-actionbaronbackpressed

How to go back to previous activite(s)?


so i have Activity A,B, and C. Activity A & B both go to activity C. When i am on activity C and I press the back home button on mySupportActionBar, I want to return to the state of activity (from the state i left it in) I came from. How would i accomplish this?

Here is my onOptionsItemSelected(). So currently, it goes back to the designated parent activity i assigned in manifest to avoid my app from crashing. Because the parent activites require strings from intents.

@Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        int id = item.getItemId();
        if(id == android.R.id.home)
        {
            NavUtils.navigateUpFromSameTask(this);
        }
        return super.onOptionsItemSelected(item);
    }

I would also love to accomplish this onBackPressed().

enter image description here


Solution

  • Use android.R.id.home

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }