Search code examples
androidandroid-alertdialogonbackpressed

How to show a dialog to confirm that the user wishes to exit an activity?


Am using below onBackpress method but this not working , am still click to back button repentantly came the same activity not exit current activity please solve my problem .

   @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        // Your Dialog Code is here.

        new AlertDialog.Builder(this)
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface arg0, int arg1) {
                        ProfileActivity.super.onBackPressed();
                        finish();
                    }
                }).create().show();
    }

Solution

  • Use .setCancelable(false) with AlertDialog,

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        // Your Dialog Code is here.
    
        new AlertDialog.Builder(this)
                .setMessage("Are you sure you want to exit?")
                .setCancelable(false)
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
    
                    public void onClick(DialogInterface arg0, int arg1) {
                        ProfileActivity.super.onBackPressed();
                        finish();
                    }
                }).create().show();
    }