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