I have a dialog fragment that has a close button on it.
This dialog is called from two different activities. One uses it as a simple fragment, and one as a dialog fragment.
In its onClick method, I call requireActivity.onBackPress()
so it will close the dialog.
I don't want to call dismiss, because I have a use case in which I want the calling activity to handle it (show a confirmation dialog).
In the activity that shows it as a dialog fragment, calling the onBackPress
closes not only the dialog but also finishes the activity :scary_face
Pressing the actual back button just dismisses it though.
Any thoughts on what am I missing here?
Code from the dialog fragment:
viewBinding.closeBtn.setOnClickListener {
requireActivity().onBackPressed()
}
Code that launches the dialog fragment
SharePatientDialogFragment.newInstance(shareData)
.show(context.supportFragmentManager, "share")
CodePudding user response:
You're calling the onBackPressed()
of the activity and not from the DialogFragment.
Hence, your activity is closing, and therefore the dialog is also closing.
To fix it, you have to invoke the onBackPressed()
of the dialog fragment to ensure that the dialog fragment is dismissed.
Fragment
does not possess an onBackPressed()
method but the Dialog
class does, as so you need to check if it's a dialog and then invoke the method if available.