28

How to handle "Up" button (SDK version 11+)? I am referring to the one at the top of screen, that holds the application icon.

In Android Design articles it was named as "Up button", but I didn't found it (or similar) in KeyEvent fields.

YKa
  • 3,998
  • 4
  • 20
  • 31
Dmitry Zaytsev
  • 23,650
  • 14
  • 92
  • 146

2 Answers2

65

Implement onOptionsItemSelected() and watch for android.R.id.home "menu" events, as is described in the documentation.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // do something useful
            return(true);
    }

    return(super.onOptionsItemSelected(item));
}
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 1
    Hey i have the same problem. But do you know how to get the little arrow? I open a new Activity with the actionbar and i want to use this "up-button" to go back to the main screen. For the SearchView it switch automaticaly the button to the one with the little arrow, but how? – Informatic0re Feb 02 '12 at 18:05
  • 4
    @Mirko: If you are referring to what I think that you are referring to, try `setHomeAsUpEnabled(true)`, called on your `ActionBar`. – CommonsWare Feb 02 '12 at 18:09
1

First change your AndroidManifest.xml file to have a parent activity declared. Eg

    <activity android:name=".theory"
              android:parentActivityName=".MainActivity"
        android:label="@string/theory"
        />
    <activity android:name=".experimental"
              android:parentActivityName=".MainActivity"
        android:label="@string/exp"
        />

Do this for all the activities other than the MainActivity. Note the parentActivityName xml code

Then go to the respective java files and add the following code

    ActionBar ab = getSupportActionBar();
    ab.setDisplayHomeAsUpEnabled(true);

You have you up button enabled now.

Sri Ram
  • 11
  • 4