Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I force the Android Back button to go two steps back in the Activity stack?

I know that I can override the onKeyDown method, but I want Back to do it's thing, just twice!

like image 676
Sara Avatar asked Apr 07 '10 11:04

Sara


1 Answers

FirstActivity

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);

SecondActivity

int REQUEST_CODE = 123
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
startActivityForResult(intent, REQUEST_CODE);

(to make this pedagogic there is more code for this activity below)

ThirdActivity

@Override
public void onBackPressed() {
    // Semi ugly way of supporting that back button takes us back two activites instead of the usual one.
    setResultOkSoSecondActivityWontBeShown();
    finish();   
}

private void setResultOkSoSecondActivityWontBeShown() {
    Intent intent = new Intent();
    if (getParent() == null) {
    setResult(Activity.RESULT_OK, intent);
    } else {
        getParent().setResult(Activity.RESULT_OK, intent);
    }
}

SecondActivity (again)

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 123) {
        if (resultCode == RESULT_OK) {
            finish();
        }
    }
}
like image 158
riper Avatar answered Oct 29 '22 10:10

riper