我的工具栏中有一个 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/