Wednesday, 21 January 2015

Display Alert on Back Button Pressed in Android

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) {
                //if user pressed "yes", then he is allowed to exit from application
                finish();
            }
        });
        builder.setNegativeButton("No",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //if user select "No", just cancel this dialog and continue with app
                dialog.cancel();
            }
        });
        AlertDialog alert=builder.create();
        alert.show();
    }   
}
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 we can write our own message that will be displayed to the user in an alert. 

"builder.setPositiveButton" will set a positive button in the left side. The parameter will accept the name of that button as we can see in code it is "Yes". The same thing is set for "builder.setNegativeButton". When we set these buttons, we need to pass a listener that will be fired when the user clicks one of the buttons.

No comments:

Post a Comment