How to Add Android Exit Dialog to Your Android App

0
2833
  • In this Post I will show you how to add Android Exit Dialog to your Android App.
  • First of all I will explain you what is Android Exit Dialog. Dialog in Android is Popup which show a message or content to the App user and gives options through buttons Like Yes or Now, Allow or Cancel etc.
  • As a result Use if accidentally clicks back button instead of exiting the app a Popup will come and ask user for confirmation.

exit_dialog_2

  • Implementing Android Exit Dialog is Very simple to do. It takes only few minutes to add an Android exit dialog to your Android App.

Watch Video for detailed explanation of the code.

 

Procedure:

  1. Create new Android Studio Project or Open you Exiting Android Studio project.
  2. Go to your Java Package and open MainActivity.Java file and add Below code to your onBackPressed() method.
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.app_name);
builder.setIcon(R.mipmap.ic_launcher);
builder.setMessage("Do you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();

After adding above code to onBackPressed() method code look like below.

 

@Override
public void onBackPressed() {

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.app_name);
builder.setIcon(R.mipmap.ic_launcher);
builder.setMessage("Do you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();

}

Hope you understood the method well. If you found this method useful share it and help others.

If you like Donate for My work: [paypal_donation_button]

LEAVE A REPLY

Please enter your comment!
Please enter your name here