【问题标题】:How to hide soft keyboard for a SearchView in Kotlin?如何在 Kotlin 中隐藏 SearchView 的软键盘?
【发布时间】:2021-03-02 07:53:01
【问题描述】:

我的工具栏中有一个 SearchView,然后在设置中用户可以启用或禁用虚拟键盘,因为他可以使用带有物理键盘的设备。

对于一个常见的 EditText,我使用以下代码禁用软键盘:

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

虽然相同的代码不适用于 SearchView,所以我尝试了一个在 stackoverflow 周围找到的函数,但即使这样也不起作用,这是我尝试过的:

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)
}

但这没有任何效果,那么我如何以编程方式禁用 SearchView 的虚拟键盘?

【问题讨论】:

  • 我已经很好地查看了源代码,我几乎可以保证没有办法干净地做到这一点,我想你不是在寻找反射等解决方案?

标签: android kotlin searchview


【解决方案1】:


您想在用户设置中完全禁用软键盘。
请尝试我的解决方案来完全禁用软输入键盘:

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

当然,您可以随时恢复并允许触发软输入键盘:

window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)

如果您愿意,请通过here 阅读有关此标志的信息

【讨论】:

  • 这是否仅对我设置标志的活动禁用键盘?
  • @IgorMytyuk 是的,我们将标志添加到活动的窗口属性中
猜你喜欢
  • 1970-01-01
  • 2020-10-18
  • 2023-01-09
  • 2011-12-24
  • 1970-01-01
  • 2017-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多