Saturday, February 16, 2013

Adding "Home as Up" Using ActionbarSherlock

"Home as Up" is part of the Actionbar design pattern in the Android Design Guide. This feature is part of an app when there is a small arrow to the left of the app icon in the Actionbar.  Implementation is simple. This post will use the ActionbarSherlock library.

In the Activities where the "Home as Up" should be displayed, in the onCreate() method get the Actionbar and then call setDisplayHomeAsUpEnabled(true)

...

ActionBar actionBar = getSupportActionBar();

actionBar.setDisplayHomeAsUpEnabled(true);

...


The second part of the implementation is to code what should happen if "Home as Up" is selected.  This is done in onOptionsItemSelected()

@Override
public boolean onOptionsItemSelected(MenuItem item) 
{
     int itemId = item.getItemId();
     switch (itemId)
     {
         case R.id.ddg:
             Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://developer.android.com/design/index.html"));
             startActivity(browserIntent);
         case android.R.id.home:
             Intent mainIntent = new Intent(getApplicationContext(), MainActivity.class);
             mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
             startActivity(mainIntent);
         default:
             break;
     }

     return true;
 }

If you have an Activity where you do not want "Home as Up", set
setDisplayHomeAsUpEnabled(false);

If your app is written to have a tablet view (master/detail), "Home as Up" will not be displayed in landscape, but will be displayed in portrait.

Droid Design Guide is an open source app that has examples of using this feature. The code is in GitHub.