简体   繁体   中英

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.

You could try

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

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 .

尝试删除包含finish()的行。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM