1

I want to put a message "Are you sure you want to exit?" and "yes" - "no" from my application when I press the "BACK" button..it's possible? how could I do to do it? thanks

Francesca
  • 59
  • 1
  • 2
  • 11
  • [http://stackoverflow.com/questions/10905945/android-prompting-an-alertdialog-onbackpressed](http://stackoverflow.com/questions/10905945/android-prompting-an-alertdialog-onbackpressed) – M D Mar 31 '15 at 08:52

2 Answers2

2
@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
        .setTitle("Really Exit?")
        .setMessage("Are you sure you want to exit?")
        .setNegativeButton(android.R.string.no, null)
        .setPositiveButton(android.R.string.yes, new OnClickListener() {

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

Taken from this answer.

Community
  • 1
  • 1
Gunaseelan
  • 14,415
  • 11
  • 80
  • 128
  • I have two swipe tabs..I put it in main activity or in the two tabs? – Francesca Mar 31 '15 at 08:49
  • [http://stackoverflow.com/questions/10905945/android-prompting-an-alertdialog-onbackpressed](http://stackoverflow.com/questions/10905945/android-prompting-an-alertdialog-onbackpressed) – M D Mar 31 '15 at 08:52
  • @Gunaseelan thank you :) but if I press "yes" on the back, after if I re-open my application, buttons don't work..why? – Francesca Mar 31 '15 at 08:57
  • If you have `super.onBackPressed()` outside the onClick please remove it. – Gunaseelan Mar 31 '15 at 09:01
0

Add your code snippet for alert dialogue in

@Override
    public void onBackPressed() {
    final AlertDialog alert = new AlertDialog.Builder(new ContextThemeWrapper(contextForAlert,R.style.CustomAlertDialogue)).create();
    alert.setTitle(title);
    alert.setMessage(message);
    alert.setIcon(R.drawable.warning_icon);
    alert.setCancelable(false);
    alert.setCanceledOnTouchOutside(false);
    alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int which) {



    }
    });


    alert.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

            alert.dismiss();    

         }
        });



    alert.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {


            }
        });

    alert.show();
    }
Don Chakkappan
  • 7,397
  • 5
  • 44
  • 59