Android Back Button Doesn't Return to Previous Activity

Dan Taylor picture Dan Taylor · Jul 14, 2013 · Viewed 15.9k times · Source

I have an app that has two activities: MainActivity and SettingsActivity. The MainActivity has a menu with a single Settings menu item. When this menu item is clicked, it launches the SettingsActivity with an intent. After the activity starts up, I click the back button in the top left corner and nothing happens. I assumed since I started the activity using an intent, the activity stack would be managed automatically. I want to return to the MainActivity. Am I wrong in this assumption?

MainActivity.onMenuItemSelected

public boolean onMenuItemSelected(int featureId, MenuItem item) {
    int itemID = item.getItemId();

    if(itemID == R.id.settings) {
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);
    }

    return true;
}

SettingsActivity

public class SettingsActivity extends PreferenceActivity {

    public static final String TEST = "test";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }
}

Answer

Shobhit Puri picture Shobhit Puri · Jul 14, 2013

Inside your SettingsActivity you need to override onOptionsItemSelectedto enable the back button on top left corner of Action Bar for going back. It does not know by itself that what it needs to do on click. Inside the case android.R.id.home you can just call finish(). This will finish your current activity and you will go back to MainActivity which started it. Eg:

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

Just for completeness, to enable the home button, you may add the following in your onCreate() of SettingsActivity:

getActionBar().setDisplayHomeAsUpEnabled(true);

As per docs of setDisplayHomeAsUpEnabled()

It is to show the user that selecting home will return one level up rather than to the top level of the app.

Hope this helps.