Search code examples
androidkotlinonbackpressed

How to invoke onBackPressedDispatcher?.onBackPressed() from the fragment?


I am a little stuck in the implementation of onBackPressedDispatcher?.onBackPressed() in the fragment

I have an Activity and Fragment within

I have a flow in the Fragment -> when a user clicks back button I need to show a dialog where it asks "Are you sure?" and once a user clicks "Yes" I have to go back.

So, in order to do so I did in my Fragment ->

...
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val callback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                showAlertDialog(
                    message = getString(R.string.myText),
                    dialogCallback = object : AlertDialogInterface {
                        override fun onAlertDialogButtonClicked(alertDialog: AlertDialog?) {}

                        override fun onPositiveButtonClicked(alertDialog: AlertDialog?) {
                            isEnabled = false
                            alertDialog?.dismiss()
                            activity?.onBackPressedDispatcher?.onBackPressed()
                        }

                        override fun onNegativeButtonClicked(alertDialog: AlertDialog?) {
                            alertDialog?.dismiss()
                        }
                    }
                    )
            }
        }

        activity?.onBackPressedDispatcher?.addCallback(
            this,
            callback
        )
    }
...

So, I assume that once a user clicks "Yes" on the dialog it triggers this event onPositiveButtonClicked and in order to pass this event further I invoke this line -> activity?.onBackPressedDispatcher?.onBackPressed(), but it goes in a circle instead.

What am I missing here?


Solution

  • Finally it has been solved like this:

    override fun onPositiveButtonClicked(alertDialog: AlertDialog?) {
        isEnabled = false
        alertDialog?.dismiss()
        callback.remove()
        activity?.onBackPressedDispatcher?.onBackPressed()
    }
    

    Once the callback is not needed, it could be removed