Arnab Chakraborty
Arnab Chakraborty

Reputation: 7472

Android : startActivityForResult() with BACK button functionality

I would like to start a new activity for a result, with startActvityForResult(), but I would like to have the back button working as normal in the new activity.

Currently when I invoke a new Activity for result, nothing happens when I press the back button in the new Activity.

I tried something like this:

@Override
public void onBackPressed() {
    setResult(0);
    super.onBackPressed();
    finish();
}

in the new Activity, but it didn't work. Still nothing happens when the back button is pressed.

Is there a way around this?

EDIT : I could of course load the last Activity in the onBackPressed() (can I?), but it seems like a rather crappy hack.

Alex Ady's answer solves my problem, but I still don't understand why onBackPressed() doesn't work. The working code now is something like this:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        setResult(1);
        finish();
    }
    return super.onKeyDown(keyCode, event);
}

I could use an explanation.

Upvotes: 12

Views: 8696

Answers (3)

Brigham
Brigham

Reputation: 14524

You shouldn't have to override the Back button behavior at all. By default, if the user presses the back button, the result will be Activity.RESULT_CANCELED.

Upvotes: 8

user874649
user874649

Reputation:

You could try

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
         finish();
    }
    return super.onKeyDown(keyCode, event);
}

Upvotes: 14

JVM
JVM

Reputation: 21

Try getting rid of the line that contains the finish().

Upvotes: 0

Related Questions