I have issue with hiding the bottomsheetfragment
and the keyboard with one back click. the current implementation require user to click back twice to close keyboard and bottomsheet.
I implement setOnKeyListener
but the first back click hide keyboard and second click fire the back event
the dialog style
<style name="BottomSheetDialog" parent="Theme.Design.Light.BottomSheetDialog">
<item name="android:windowIsFloating">false</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:windowSoftInputMode">adjustResize</item>
</style>
class CommentInputFragment : BottomSheetDialogFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(DialogFragment.STYLE_NORMAL, R.style.BottomSheetDialog);
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
var view= inflater.inflate(R.layout.fragment_comment_input, container, false)
return view;
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
var dialog= super.onCreateDialog(savedInstanceState)
return dialog
}
override fun onResume() {
super.onResume()
dialog?.setOnKeyListener(object: DialogInterface.OnKeyListener
{
override fun onKey(p0: DialogInterface?, keyCode: Int, p2: KeyEvent?): Boolean {
if ((keyCode == android.view.KeyEvent.KEYCODE_BACK))
{
// To dismiss the fragment when the back-button is pressed.
dismiss();
return true;
}
// Otherwise, do nothing else
else return false;
}
})
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
et_add_comment.requestFocus();
}
}
Problem:
The back press won't be intercepted by the dialog in this case as it's trigger by the soft keyboard, if you notice that the back arrow points to the bottom (in recent devices) not to the left. Therefore the callback of the
dialog?.setOnKeyListener
won't be triggered.So, you need to intercept the key event by some keyboard listener; well this is a challenge as per many posts like here, and there, and each solution can work in particular cases.
Solution
We will register a listener to the root
ViewGroup
of theBottomSheetFragment
layout (R.layout.fragment_comment_input
) whendispatchKeyEventPreIme()
is called. This gets called for the key events attached to this layout.Create the listener:
So, as the root is
FrameLayout
, then customize it:And use it as the root layout in the
R.layout.fragment_comment_input
:Then set the listener in the
BottomSheetFragment
onResume()
to dismiss the dialog.And now you can safely remove
dialog?.setOnKeyListener
Preview: