Search code examples
androidkotlinsearchview

How to hide soft keyboard for a SearchView in Kotlin?


I have a SearchView in my Toolbar, then in the settings the user could enable or disable the virtual keyboard as he could use a device with the physical keyboard.

For a common EditText i use the following code to disable the soft keyboard:

if (!keyboard) {
    txtBarcode.showSoftInputOnFocus = false
    txtQta.showSoftInputOnFocus = false
}else {
    txtBarcode.showSoftInputOnFocus = true
    txtQta.showSoftInputOnFocus = true
}

While the same code doesn't work for the SearchView, so i've tryed with a function found around stackoverflow but even that doesn't work, here is what i've tryed:

override fun onPrepareOptionsMenu(menu: Menu) {
    super.onPrepareOptionsMenu(menu)
    val item: MenuItem = menu.findItem(R.id.app_bar_search)
    val searchView: SearchView = item.actionView as SearchView

    val prefs = PreferenceManager.getDefaultSharedPreferences(requireContext())
    val keyboard = prefs.getBoolean("keyboard", true)
    inputModeChange(searchView, keyboard);
    item.isVisible = true

}

private fun inputModeChange(editText:SearchView, showKeyboard:Boolean) {
    editText.postDelayed({
        if (showKeyboard) {
            val keyboard = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            keyboard.showSoftInput(editText, 0)
        } else if (!showKeyboard) {
            val imm = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(editText.windowToken, 0)
        }
    }, 50)
}

But that doesn't had any effect, so how could i programmatically disable the virtual keyboard for SearchView?


Solution


  • You wanted to completely disable the soft keyboard in user's settings.
    Kindly try my solution to completely disable soft input keyboard:

    window.setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
                                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
    

    Of course you can always revert back and allow the trigger of soft input keyboard with:

    window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
    

    Read about this flag over here if you like