Saturday 6 March 2021

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?



from How to hide soft keyboard for a SearchView in Kotlin?

No comments:

Post a Comment