Make application icon clickable on the Action Bar

Description

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


@Override/*from  ww  w  .  j a v  a  2s  . c om*/
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)
{/*www  . ja  v a 2 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  /*  w  ww . ja va2s  . c  om*/
  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.





















Home »
  Android »
    Android UI »




UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView