@Override
public void onBackPressed() {
// If the pet hasn't changed, continue with handling back button press
if (!mPetHasChanged) {
super.onBackPressed();
return;
}
// Otherwise if there are unsaved changes, setup a dialog to warn the user.
// Create a click listener to handle the user confirming that changes should be discarded.
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// User clicked "Discard" button, close the current activity.
finish();
}
};
// Show dialog that there are unsaved changes
showUnsavedChangesDialog(discardButtonClickListener);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// User clicked on a menu option in the app bar overflow menu
switch (item.getItemId()) {
// Respond to a click on the "Save" menu option
case R.id.action_save:
savePet();
return true;
// Respond to a click on the "Delete" menu option
case R.id.action_delete:
showDeleteConfirmationDialog();
return true;
// Respond to a click on the "Up" arrow button in the app bar
case android.R.id.home: {
// If the pet hasn't changed, continue with navigating up to parent activity
// which is the {@link CatalogActivity}.
if (!mPetHasChanged) {
NavUtils.navigateUpFromSameTask(EditorActivity.this);
return true;
}
// Otherwise if there are unsaved changes, setup a dialog to warn the user.
// Create a click listener to handle the user confirming that
// changes should be discarded.
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// User clicked "Discard" button, navigate to parent activity.
NavUtils.navigateUpFromSameTask(EditorActivity.this);
}
};
// Show a dialog that notifies the user they have unsaved changes
showUnsavedChangesDialog(discardButtonClickListener);
return true;
}
}
return super.onOptionsItemSelected(item);
}
I got this code from online course, and i'm confused why should we override onBackPressed()? I mean, in onOptionsItemSelected method, when the id is the same as android.R.id.home, the code is similiar to the code on onBackPressed method. Any explanation why they take this approach to show the dialogue? Can we not to override the onBackPressed method?