现象:应用首次安装,点击搜索。弹起键盘。退出应用,键盘收起又弹出
fun hideSoftKeyboard(editText: EditText?) {
if (editText != null) {
val imm = editText.context
.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(editText.windowToken, 0)
}
}
fun showSoftKeyboard(editText: EditText?) {
if (editText != null) {
val imm = editText.context
.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0)
}
}
原因:
可能是使用了toggleSoftInput方法导致的,show和hide要成对使用,官方不建议使用toggleSoftInput。
解决方案:
fun hideSoftKeyboard(editText: EditText?) {
if (editText != null) {
val imm = editText.context
.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(editText.windowToken, 0)
}
}
fun showSoftKeyboard(editText: EditText?) {
if (editText != null) {
val imm = editText.context
.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(editText,0)
}
}