OnBackPressedCallback not called - Activitiy is terminated immediately

259 Views Asked by At

Hello,

adding OnBackPressedDispatcher and OnBackPressedCallback in my MainActivity cause onBackPressedwas deprecated.

old usage:

   @Override
public void onBackPressed() {
    //Display alert message when back button has been pressed
    alertDialogShow();
}

New usage: put it in my initialize listener call in MainActivity onCreate() - initListeners()

    onBackPressedCallback = new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {
            //Display alert message when back button has been pressed
            alertDialogShow();
        }
    };

    onBackPressedDispatcher = new OnBackPressedDispatcher();
    onBackPressedDispatcher.addCallback(this,onBackPressedCallback);

but the method alterDialogShow() is never called and the activity is terminated immediately. How can I solve this.

Thanks, Alejandro

2

There are 2 best solutions below

0
hata On BEST ANSWER

You create a new OnBackPressedDispatcher but you must use the Activity's OnBackPressedDispatcher and add your callback to it:

//onBackPressedDispatcher = new OnBackPressedDispatcher();
onBackPressedDispatcher = getOnBackPressedDispatcher();

onBackPressedDispatcher.addCallback(this, onBackPressedCallback);
0
MãĴď On

Following on my comment above. this is one way to do it.

   OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {
            // Create an AlertDialog to confirm the action
            new AlertDialog.Builder(YourActivity.this)
                .setTitle("Confirm Action")
                .setMessage("Are you sure you want to go back?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // Perform the desired action when the user confirms
                        // For example, you can call super.onBackPressed() to go back
                        super.onBackPressed();
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // Do nothing or handle the cancel action here
                    }
                })
                .show();
        }
    };

    // Add the callback to the back stack
    getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);
}