just create an extension function to the fragment
fun Fragment.onBackPressedAction(action: () -> Boolean) {
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object :
OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
this.isEnabled = action()
if (!this.isEnabled) {
requireActivity().onBackPressed()
}
}
})
}
and after in the fragment put the code into onCreateView (the action must return false to call the activity onBackPressed)
onBackPressedAction { //do something }