使用以下内容覆盖活动的 onBackPressed,以防您对某些值进行了更改并且之后忘记更新这些值,而是按下了后退按钮:
@Override
public void onBackPressed() {
if( <condition>) {
AlertDialog.Builder ad = new AlertDialog.Builder( this);
ad.setTitle("Changes were made. Do you want to exit without update?");
ad.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
backPress();
}
}
);
ad.setNegativeButton(
"Update the changes",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
<Update the changes>;
Toast.makeText(getApplicationContext(), "Changes were updated", Toast.LENGTH_SHORT).show();
backPress();
}
}
);
ad.setCancelable( false);
ad.show();
} else {
backPress();
}
}
private void backPress() {
super.onBackPressed();
}