Add back button to action bar
Solution 1:
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);
}
}
Solution 2:
Add
actionBar.setHomeButtonEnabled(true);
and then add the following
@Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
As suggested by naXa I've added a check on the itemId
, to have it work correctly in case there are multiple buttons on the action bar.
Solution 3:
this one worked for me:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_your_activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ... other stuff
}
@Override
public boolean onSupportNavigateUp(){
finish();
return true;
}
The method onSupportNavigateUp() is called when you use the back button in the SupportActionBar.
Solution 4:
After setting
actionBar.setHomeButtonEnabled(true);
You have to configure the parent activity in your AndroidManifest.xml
<activity
android:name="com.example.MainActivity"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat" />
<activity
android:name="com.example.SecondActivity"
android:theme="@style/Theme.AppCompat" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.MainActivity" />
</activity>
Look here for more information http://developer.android.com/training/implementing-navigation/ancestral.html