how to override action bar back button in android?
Solution 1:
I think you want to override the click operation of home button. You can override this functionality like this in your activity.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
Solution 2:
If you want ActionBar back button behave same way as hardware back button:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return false;
}
Solution 3:
Two things to keep in mind that the user can either press back button or press the actionbar home button.
So, if you want to redirect him to the same destination then you can do this.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return false;
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
startActivity(intent);
finish();
}
This will take the user to the intent pressing either key or the action bar button.
Solution 4:
Sorry mine is a late answer, but for anyone else arriving at this page with the same question, I had tried the above:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
...
if (item.getItemId() == android.R.id.home) {
....
}
....
}
but this failed to catch the "Back" button press.
Eventually I found a method that worked for me on https://stackoverflow.com/a/37185334/3697478 which is to override the "onSupportNavigateUp()" as I am using the actionbar from the "AppCompatActivity" support library. (There is an equivalent "onNavigateUp()" for the newer actionbar/toolbar library.)
@Override
public boolean onSupportNavigateUp(){
finish();
return true;
}
and I removed the "android:parentActivityName=".MainActivity" section from the manifest file.