Add back button to action bar

haythem souissi picture haythem souissi · Aug 22, 2012 · Viewed 141.6k times · Source

I have been trying to add a back button to the action bar.

I want my view to look like this: enter image description here

I want to add the back button in the left of the action bar.

I added this code

ActionBar actionBar = getActionBar();

actionBar.setDisplayHomeAsUpEnabled(true);

but it doesn't work.

How can I fix this?

Answer

Danesh picture Danesh · Dec 6, 2012

After setting actionBar.setHomeButtonEnabled(true);

Add the following code:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // app icon in action bar clicked; goto parent activity.
            this.finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}