android - 如何在 Kotlin 中隐藏 SearchView 的软键盘?

标签 android kotlin searchview

我的工具栏中有一个 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 的虚拟键盘?

最佳答案


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

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

当然你总是可以返回并允许触发软输入键盘:

window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)

通过 here 了解此标志如果你喜欢

关于android - 如何在 Kotlin 中隐藏 SearchView 的软键盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66435336/

相关文章:

带有自定义建议适配器的 Android SearchView

solr - 限制用户访问的 Lucene 索引

android - Web API 服务器 Controller 未获取参数

android - 我想从我的 flutter 应用程序启动 WhatsApp 应用程序

android - Kotlin 迁移后 Crashlytics 报告错误的行号

android - Dagger 柄 : Repository cannot be provided without an @Provides-annotated method

android - 从 MenuItem 获取 SearchView 返回 View 而不是 SearchView

java - Android - 使用 XPath 解析 XML

java - Android:在 AsyncTask 中 toast

android - 仅使用 AndroidJunit4 时日历测试通过