-1

I have an android app that has a timer that when expires plays a sound.

I have the following code to capture when a user tries to navigate away from the fragment;

public void onPause() {
    super.onPause();
    if (gameOn == 1) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setMessage("Are you sure you want to cancel the match?")
                .setCancelable(false)
                .setTitle("Cancel match?")
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        //do things
                    }
                });
        AlertDialog alert = builder.create();
            alert.show();
    }
}

The problem I have is I want to add in an additional option (YES / NO, which I know how to do) that suppresses the user from navigating away without making the choice too (the UI could mean a user accidentally navigates away from the fragment, this is a fail safe, are you really sure question).

onPause does trigger the alert dialog to pop-up but behind it the new fragment has already loaded and as far as I'm aware onPause is the first of the events triggered when a user moves away from a fragment.

All help appreciated.

Carl Bruiners
  • 516
  • 1
  • 7
  • 21
  • Why don't you simply use a [DialogFragment](https://developer.android.com/reference/android/app/DialogFragment.html) with `setCancelable(false)`? – Bö macht Blau Mar 10 '18 at 17:18

1 Answers1

1

When onPause() is called it's already too late to undo the transaction. It's committed. I cannot see how many click options you have in your fragment to navigate away but I can suggest to add in onClickListeners this alert dialogue you create wherever you need your additional "check". You could make it a separate method showDialogue for example and put you code there and then call it onclick. So you won't have repeated code. The in positive button click segment you just put your fragmenttransaction code.

Maybe you'll need to override the backpress too. Refer this link

Rainmaker
  • 10,294
  • 9
  • 54
  • 89