简体   繁体   中英

Prevent dismissal of BottomSheetDialogFragment if keyboard is visible

I have a use case where a BottomSheetDialogFragment is having an edit text and this edit text is in focus. And keyboard is open on top of BottomSheetDialogFragment. The requirement is when a user clicks outside of dialog, first keyboard should be dismissed without dismissing the dialog. This gives the user a chance to re-click on edit text and keyboard reappears. And once keyboard is in hidden state, then if user clicks outside of dialog, then dialog is dismissed. But this is not happening when user clicks outside of dialog and keyboard is visible then dialog is dismissed. How can i intercept the touch events to alter this behaviour?

This is a tricky one. Something you could do, is to add a listener for whenever the keyboard is visible like they do here , and make your BottomSheetDialogFragment cancellable whenever it is not showing, and non-cancellable whenever it is by callling

bottomSheetDialog.isCancellable = true/false

I can think of two ways to achieve this.
First is to override `BottomSheetDialogFragment#onCreateDialog` method and provide a custom dialog like this
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = object: BottomSheetDialog(requireContext()) { override fun onTouchEvent(event: MotionEvent): Boolean { /* detect touch outside here and hide keyboard */ return super.onTouchEvent(event) } } return dialog.apply { setCanceledOnTouchOutside(false) setContentView(R.layout.bottom_sheet_layout) } }

Second one is creating your own bottom sheet dialog fragment by using a full screen DialogFragment , CoordiatorLayout and BottomSheetBehavior and detect whenever root container was clicked and do things based on your requirements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM