Reputation: 463
I am trying to show a confirm AlertDialog before user press on back button or Activity going Pause.
I tried this code:
@Override
public void onBackPressed() {
super.onBackPressed();
AlertDialog.Builder confirmBuilder=new AlertDialog.Builder(DoExam.this);
confirmBuilder.setTitle("Confirm Exit");
confirmBuilder.setMessage("are you sure to exit form this activity");
confirmBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
confirmBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog confirmDialog=confirmBuilder.create();
confirmDialog.show();
}
But it disappeared immediately at the same time the app back to previous activity.
I tried also to put the code at onPause method but I got the same problem.
Any help about show alert dialog and back to previous activity if clicked yes and keep user in the Activity if clicked no?
Upvotes: 2
Views: 82
Reputation: 434
use this code
@Override
public void onBackPressed() {
AlertDialog.Builder confirmBuilder=new AlertDialog.Builder(DoExam.this);
confirmBuilder.setTitle("Confirm Exit");
confirmBuilder.setMessage("are you sure to exit form this activity");
confirmBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do any action you require on click
DoExam.super.onBackPressed();
}
});
confirmBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog confirmDialog=confirmBuilder.create();
confirmDialog.show();
}
Upvotes: 1
Reputation: 11477
Remove
super.onBackPressed();
and add it inonClick(...)
of your posetive Yes button of your Alertdialog..
like this
confirmBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { super.onBackPressed();
} });
Upvotes: 1
Reputation: 3863
Because you are calling super.onBackPressed();
remove that and see what happens. the super.onBackPressed();
is meant to trigger the default action of closing the activity. you need to defer that call when the user dismisses the dialog.
Upvotes: 2