Android UI How to - Make application icon clickable on the Action Bar








To make the application icon clickable, you need to call the setDisplayHomeAsUpEnabled() method:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

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

}

When the application icon is clicked, the onOptionsItemSelected() method is called.

To identify the application icon being called, you check the item ID against the android.R.id.home constant:

private boolean MenuChoice(MenuItem item)
{//from w  w w  . j a v  a2  s.  c  o  m
   switch (item.getItemId()) {
     case  android.R.id.home:
           Toast.makeText (this,"You clicked on the Application icon",Toast.LENGTH_LONG).show();
           return true;
     case 0:
           Toast.makeText (this, "You clicked on Item 1",Toast.LENGTH_LONG).show();
           return true;
     case 1:
            //...
   }
   return false;
}

We can use application icon to return to the main activity. To do this, we can create an Intent object and set it using the Intent.FLAG_ACTIVITY_CLEAR_TOP flag:

case  
  android.R.id.home :
    Toast.makeText (this,"You clicked on the Application icon",Toast.LENGTH_LONG).show();
    Intent i = new Intent(this, MyActionBarActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
    return true;

The Intent.FLAG_ACTIVITY_CLEAR_TOP flag ensures that the series of activities in the back stack is cleared.