Question

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);
    }
}
Was it helpful?

Solution

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.

OTHER TIPS

Just add these lines in your OnCreate methord

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

and override this method to add functionality to your back button:

   @Override
public boolean onOptionsItemSelected(MenuItem item)
{
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    } else if(id==android.R.id.home)
    {
     finish();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

Hope it helps you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top