I'm trying to handle the back button in a BottomSheetDialogFragment
, which is a DialogFragment
, using 'androidx.activity:activity-ktx:1.1.0-alpha01'
and 'androidx.fragment:fragment-ktx:1.2.0-alpha01'
.
handleOnBackPressed()
is not called and the DialogFragment
is dismissed. The OnBackPressedCallback
is enabled when the back button is pressed.
I think the DialogFragment
is intercepting the back button press, because the ComponentActivity
never calls mOnBackPressedDispatcher.onBackPressed();
Is there a way to override the DialogFragment
handling of back button press?
I found a solution, but I hope the library will take care of this usecase.
Create a custom BottomSheetDialog
:
class BackPressBottomSheetDialog(context: Context, @StyleRes theme: Int,
private val callback: BackPressBottomSheetDialogCallback) :
BottomSheetDialog(context, theme) {
override fun onBackPressed() {
if (callback.shouldInterceptBackPress()) callback.onBackPressIntercepted()
else super.onBackPressed()
}
}
And its interface
interface BackPressBottomSheetDialogCallback {
fun shouldInterceptBackPress(): Boolean
fun onBackPressIntercepted()
}
Then in your BottomSheetDialogFragment
private val dialogCallback = object : BackPressBottomSheetDialogCallback {
override fun shouldInterceptBackPress(): Boolean {
//TODO should you intercept the back button?
}
override fun onBackPressIntercepted() {
//TODO what happens when you intercept the back button press
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return BackPressBottomSheetDialog(requireContext(), theme, dialogCallback)
}