0

i am creating a quiz app in witch: when use choose an answer user will be navigate to next screen.

what i want begins here:

i want to prevent user to go back to previous screen,

if user try to go back to previous screen by taping back button, a exit confirm message should appear.

if user choose "OK" the app should close and if user choose "CANCEL / (Continue Quiz)" the app should continue from current screen.

user3441251
  • 27
  • 2
  • 7

2 Answers2

2

You need to override in your activity onBackPressed in this way

    @Override
public void onBackPressed() {
    AlertDialog dlg = new AlertDialog.Builder(YourActivity.this).create();
    dlg.setCancelable(false);
    dlg.setTitle("CLOSE");
    dlg.setMessage("Are you sure?");
    dlg.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    dlg.setButton(DialogInterface.BUTTON_POSITIVE, "CLOSE APP", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            YourActivity.super.onBackPressed();
        }
    });

    dlg.show();
}
Rino
  • 733
  • 8
  • 19
  • 1
    I would recommend using `ActivityName.super.onBackPressed()` instead of `finish()` in the onClick for the positive button. – BVB Mar 21 '14 at 17:23
0

You can override the onBackPressed() function in your Activity.

@Override
public void onBackPressed() {
    // code for displaying confirm message here
}

This answer has sample code for creating a confirmation dialog box: https://stackoverflow.com/a/6413736/379245

Community
  • 1
  • 1
BVB
  • 5,380
  • 8
  • 41
  • 62