Search code examples
androidandroid-softkeyboardandroid-bottomsheetdialog

Show keyboard when BottomSheet opens


I want the keyboard to appear automatically when certain fragments are open in my application. To this end, I created an extension function showKeyboard():

fun EditText.showKeyboard() {
    this.requestFocus()
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
    imm?.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

This function works very well in fragments, but for some reason, it doesn't work in BottomSheets.

Here's how I use it in fragments (this works ✅ ):

override fun onResume() {
    super.onResume()
    binding.nickEdit.showKeyboard()
}

Here's how I use it in BottomSheet (this doesn't work ❌):

override fun onResume() {
    super.onResume()
    binding.searchEdit.showKeyboard()
}

I have tried adding showkeyboard() function to onViewCreated(), but the keyboard still doesn't appear when the BottomSheet opens. How can I fix this?


Solution

  • I solved this issue by adding windowSoftInputMode attribute to my BottomSheet style and setting the value to adjustResize. Here's the full version of my BottomSheet style:

    <style name="MyBottomSheetDialogTheme" parent="Theme.Design.Light.BottomSheetDialog">
        <item name="bottomSheetStyle">@style/MyBottomsheetStyle</item>
        <item name="colorPrimary">@color/white</item>
        <item name="colorAccent">@color/white</item>
        <item name="colorControlNormal">@color/white</item>
        <item name="android:windowIsFloating">false</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
        <item name="android:windowSoftInputMode">adjustResize</item>
    </style>
    
    <style name="MyBottomsheetStyle" parent="Widget.Design.BottomSheet.Modal">
        <item name="android:background">@drawable/background_bottom_sheet</item>
    </style>