Question

I use ActionbarSherlock and would like to enable the home button ...
Therefore I call setHomeButtonEnabled(true) in my base activity.

public class BaseFragmentActivity extends SherlockFragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.Theme_Sherlock);
        super.onCreate(savedInstanceState);
        getSupportActionBar().setHomeButtonEnabled(true); // Here
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home: {
                Intent intent = new Intent(this, HomeActivity.class);
                // startActivity(intent);
                // startActivityIfNeeded(intent, 0);
                return true;
            }
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

When I use startActivity(intent) or startActivityIfNeeded(intent, 0) the HomeActivity is recreated everytime (the activity renders a map and recreating it is annoying).

  • I do not want to call finish() since it just takes me back one step in the app hierarchy. Instead I always want to return to the HomeActivity.
  • Further it would be nice if the behavior could be configured in AndroidManifest.xml as it is described for the ActionBar and setDisplayHomeAsUpEnabled().
  • It might also be common sense to clear the backstack when I return to the HomeActivity. What is your opinion on that?
Was it helpful?

Solution 2

In the Android documentation I found what I was searching for: You can set the flag FLAG_ACTIVITY_CLEAR_TOP to clear the back stack. The second flag FLAG_ACTIVITY_SINGLE_TOP avoid restarting the activity if used in combination with the flag mentioned before.

case android.R.id.home: {
    Intent intent = new Intent(this, HomeActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    startActivityIfNeeded(intent, 0);
    return true;
}

The intent needs to be passed using startActivityIfNeeded().

OTHER TIPS

I'd consider using the single instance launchmode for that activity.

AndroidManifest.xml

<activity  android:launchMode="singleInstance">
...
</activity>

Reference

Only allow one instance of this activity to ever be running. This activity gets a unique task with only itself running in it; if it is ever launched again with the same Intent, then that task will be brought forward and its Activity.onNewIntent() method called. If this activity tries to start a new activity, that new activity will be launched in a separate task. See the Tasks and Back Stack document for more details about tasks.

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