How to enable the Android ActionBar activity icon to “tap to go home”

If you want to enable the Android activity icon (app icon) in your application's ActionBar so users can tap the icon to go to the home screen, here are my notes on how to do this.

Enabling the ActionBar activity icon to handle the home button tap is a simple, three step process:

Step 1

In Step 1, add a line like this to your app's AndroidManifest.xml file:

<uses-sdk android:minSdkVersion="11" android:targetSdkVersion="15" />

At this moment I don't remember the correct minSdkVersion or targetSdkVersion you have to use; I think it may be "8", but I need to look it up. But anything greater than that number is what you need to get started. (I'm writing these notes a few weeks after getting this to work, so this step in particular is a little fuzzy.)

Step 2

In Step 2, in the Activity where you want to let the user tap the app icon, add one line of code to your onCreate method:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // enables the activity icon as a 'home' button. required if "android:targetSdkVersion" > 14
    getActionBar().setHomeButtonEnabled(true);
}

Step 3

In Step 3, add (or modify) the onOptionsItemSelected method, so it handles the special android.R.id.home event, as shown here:

/**
 * Let's the user tap the activity icon to go 'home'.
 * Requires setHomeButtonEnabled() in onCreate().
 */
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
    switch (menuItem.getItemId()) {
        case android.R.id.home:
            // ProjectsActivity is my 'home' activity
            startActivityAfterCleanup(ProjectsActivity.class);
            return true;
    }
    return (super.onOptionsItemSelected(menuItem));
}

private void startActivityAfterCleanup(Class<?> cls) {
    if (projectsDao != null) projectsDao.close();
    Intent intent = new Intent(getApplicationContext(), cls);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
}

Your code to handle the activity icon tap action can be simpler (or more complex) than what I've shown, but I hope that shows the basic idea.

Summary

To review, handling the Android ActionBar home button (icon) tap is a simple three step process:

  1. Modify your AndroidManifest file, as shown.
  2. Add one line of code to your Activity's onCreate method.
  3. Add the android.R.id.home handling code to your onOptionsItemSelected method.