Add a Back Button to an Action Bar

How to Add a Back Button to an Action Bar

1. Add an Action Bar.

3. Open the NewActivity.java file and add the below import to the imports section.

import android.app.ActionBar;
import android.view.MenuItem;

4. While in the NewActivity.java file and add the following lines of code to the onCreate method.
This will add the back button to the Action Bar. However, it will not do any action yet when pressed.

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

5. In the NewActivity.java file, add the following method after the onCreate Method.

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

6. In the onOptionsItemSelected method,  Start the Activity named MainActivity in the case named home right before the return true line of code.

7. In the onOptionsItemsSelected method, before the startActivity line, add the following line.

myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

8. Compile and run!

Resources:
http://stackoverflow.com/questions/15686555/display-back-button-on-action-bar-android

Other Resources