Luis Mendo
Luis Mendo

Reputation: 112659

Capturing the behaviour of "back" button

I have an app that consists of two activities: the "main" activity (M) and the "settings" activity (S). S can only be launched from M. The purpose of S is to modify settings which affect M. S has a "done" button that finishes the activity and goes back to M (through M's onActivityResult method, with an Intent that contains the new settings for M to apply).

My problem is: if I go back from S to M using the hardware "back" button (instead of S's "done" button) the system brings M to the top without any knowledge of the modified settings. Can this behaviour be modified? Ideally I would like to alter the behaviour of the hardware "back" button when S is on top, so that it cause S to finish (that way M would get the new settings).

If that's not possible, and more generally: what would you do you to have the settings applied on a "back" button pressing?

Upvotes: 0

Views: 143

Answers (5)

Vlad K.
Vlad K.

Reputation: 320

You can also introduce a new java class to your package with static fields holding your settings.

Write to them as user changes settings & read from them as soon as in Activity's OnResume() method or later as needed.

Upvotes: 2

codeMagic
codeMagic

Reputation: 44571

You can simply override onBackPressed()

@Override
public void onBackPressed()
{
    // check if settings have been changed
    super.onBackPressed();
}

Since this is a "closing action" do the super call after you have done your other work.

Following up on comments left on blackbelt's answer (now deleted comments) you may want to consider, if you haven't already, asking the user if they are sure they want to exit without saving in case they went into settings and decided not to change anything. What if they press the back button because they decided not to save the changes? You may already have something in place for this like a cancel button.

Upvotes: 4

jacobianism
jacobianism

Reputation: 226

The answers above will do what you want, however:

Have you looked into using the built in android SharedPreferences? That way changes to the settings (made in S) will be stored to the device and then you can tell activity M to look at the settings and update appropriately in the onResume method. Plus the settings will be saved forever and it doesn't matter what happens to S.

Upvotes: 1

Gunhan
Gunhan

Reputation: 7035

You can achieve what you want by overriding onbackpressed method

@Override
public void onBackPressed() {
    Intent intent = new Intent();

    //get your settings from your views
    intent.putExtra("setting1","on");
    intent.putExtra("setting2","off");

    setResult(RESULT_OK);
    finish();
}

Upvotes: 1

Blackbelt
Blackbelt

Reputation: 157437

you have to override the onBackPressed from Activity and manage the same logic from the done button

Upvotes: 2

Related Questions