Description
When a user wants to exit from an application, he is prompted to exit from the application.
Alert means to get the user's input when needed. Most of us have played games and when we try to exit it by pressing the "Back" button on an Android phone, it will ask "Do you really want to exit?". So, this article explains how to prevent the user from exiting an application without giving a response.
Step 1
Create a new project with the following parameters.
Step 2
Open your Main Activity file, in my case, it is "BackPressActivity" and pastes the following code into it.
BackPressActivity
- package com.example.alertonbackpressdemo;
- import android.app.AlertDialog;
- import android.content.DialogInterface;
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Menu;
-
- public class BackPressActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- }
- @Override
- public void onBackPressed() {
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setCancelable(false);
- builder.setMessage("Do you want to Exit?");
- builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
-
- finish();
- }
- });
- builder.setNegativeButton("No",new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
-
- dialog.cancel();
- }
- });
- AlertDialog alert=builder.create();
- alert.show();
- }
- }
Let's understand the Alert Dialog and its various methods.
In code, we use "builder.setCancelable(false);" so that user can't cancel this dialog by pressing back again or touch outside the alert dialog box and dismiss it. So the user must press one of the options you have provided.
Next is "builder.setMessage("Do you want to Exit?");". Here you can write your own message that will be displayed to the user in an alert.
"builder.setPositiveButton" will set a positive button on the left side. The parameter will accept the name of that button as you can see in code it is "Yes". The same thing is set for "builder.setNegativeButton". When you set these buttons, you need to pass a listener that will be fired when the user clicks one of the buttons.
Step 3
Run your application.
Summary
In this article, we learned "How to show Alert Dialog" and "Show dialog at BACK button pressed".