I want to put a message "Are you sure you want to exit?" and "yes" - "no" from my application when I press the "BACK" button..it's possible? how could I do to do it? thanks
Asked
Active
Viewed 2.1k times
3 Answers
15
Yes,It is possible by alertdialog on back press of your activity,
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ExampleActivity.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
Alka Jadav
- 401
- 2
- 14
-
thanks. It is working me. it is simple solution too. we can use custom alert box for nice ui looking – Mohammed Nishar Sep 15 '18 at 11:13
2
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
WelcomeActivity.super.onBackPressed();
}
}).create().show();
}
Taken from this answer.
Community
- 1
- 1
Gunaseelan
- 12,697
- 10
- 74
- 118
-
I have two swipe tabs..I put it in main activity or in the two tabs? – Francesca Mar 31 '15 at 08:49
-
[http://stackoverflow.com/questions/10905945/android-prompting-an-alertdialog-onbackpressed](http://stackoverflow.com/questions/10905945/android-prompting-an-alertdialog-onbackpressed) – M D Mar 31 '15 at 08:52
-
@Gunaseelan thank you :) but if I press "yes" on the back, after if I re-open my application, buttons don't work..why? – Francesca Mar 31 '15 at 08:57
-
If you have `super.onBackPressed()` outside the onClick please remove it. – Gunaseelan Mar 31 '15 at 09:01
0
Add your code snippet for alert dialogue in
@Override
public void onBackPressed() {
final AlertDialog alert = new AlertDialog.Builder(new ContextThemeWrapper(contextForAlert,R.style.CustomAlertDialogue)).create();
alert.setTitle(title);
alert.setMessage(message);
alert.setIcon(R.drawable.warning_icon);
alert.setCancelable(false);
alert.setCanceledOnTouchOutside(false);
alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alert.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alert.dismiss();
}
});
alert.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
}
});
alert.show();
}
Don Chakkappan
- 7,157
- 5
- 43
- 57