Exit Dialog for Android Application

This is an example of implementing simple Exit Dialog with two options, YES, and NO. The code is simple and straight forward. All you need to do is to override onBackPressed() in your activity and add a simple AlertDialog (you can find tutorial about simple dialog here). We use Builder for doing it:

@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.super.onBackPressed(); } }) .setNegativeButton("No", null) .show(); } 1 2 3 4 5 6 7 8 9 10 11 12 13 @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 . super . onBackPressed ( ) ; } } ) . setNegativeButton ( "No" , null ) . show ( ) ; }

Or using lambda expressions:

@Override public void onBackPressed() { new AlertDialog.Builder(this) .setMessage(R.string.are_you_sure_exit) .setCancelable(false) .setPositiveButton(R.string.yes, (dialog, id) -> HomeActivity.super.onBackPressed()) .setNegativeButton(R.string.no, null) .show(); } 1 2 3 4 5 6 7 8 9 @Override public void onBackPressed ( ) { new AlertDialog . Builder ( this ) . setMessage ( R . string . are_you_sure_exit ) . setCancelable ( false ) . setPositiveButton ( R . string . yes , ( dialog , id ) -> HomeActivity . super . onBackPressed ( ) ) . setNegativeButton ( R . string . no , null ) . show ( ) ; }

When back is pressed we will have an Alert dialog looking like this:

Related