How to get the Android ActionBar Back/Up button to work like the Android back button

As a quick note, I was just in a situation where I wanted to get my ActionBar’s Back/Up button to work just like the Android back button. To get it to work like that, I used this Java code in my Fragment class:

/**
 * react to the user tapping the back/up icon in the action bar
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // this takes the user 'back', as if they pressed the left-facing triangle icon on the main android toolbar.
            // if this doesn't work as desired, another possibility is to call `finish()` here.
            getActivity().onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

A key to that code is calling this method in the switch statement:

getActivity().onBackPressed();

As noted, calling the finish() method may have the same effect -- and may, in fact, be a better approach in some situations -- but I haven’t tested that yet.

In summary, if you wanted to see how to make your ActionBar Back/Up button work just like the Android “back” button -- the triangle that points to the left -- I hope this source code is helpful.