Home > Articles > Mobile Application Development & Programming

  • Print
  • + Share This
From the author of Handling Application Icon Clicks on the Action Bar

Handling Application Icon Clicks on the Action Bar

Another feature of the action bar is that the user can click the application icon in the top-left corner. Although clicking does nothing by default, adding a custom "home" functionality, perhaps to your launch screen, is easy.

Let's say you want to update the default action bar in the ScrubActivity class so that clicking the application icon causes the user to return to the main launch activity (clearing the activity stack at the same time).

To do this, you would simply implement the onOptionsItemSelected() method for the ScrubActivity class and handle the special menu item identifier called android.R.id.home, like this:

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

That's all there is to it (Figure 2, bottom center). You can also display a little arrow to the left of the application icon to identify that you are moving back "up" the screen hierarchy of your application by using the setDisplayHomeAsUpEnabled() method in your activity's onCreate() method in conjunction with implementing the special home menu item click handler above.

ActionBar bar = getActionBar();
bar.setDisplayHomeAsUpEnabled(true);

The resulting action bar, if we were to enable it on the Sweep screen, is shown in Figure 7.

Figure 7 An action bar with a clickable home button and an up indicator (Click Image to Enlarge)

  • + Share This
  • 🔖 Save To Your Account