问题描述
不知道各位有没有遇到过,当Dialog
中存在EditText
并输入,在软键盘弹起时,dismiss()
Dialog
,软键盘消失后会再次弹起。如下图
??这是咋回事?我多调用了一遍键盘弹起的方法吗?还是键盘最后的倔强?
原因分析
于是百度下,有相同问题的解决方法是在dismiss()
时,在多调用一下关闭键盘的方法。。。简单暴力。。。
多关弹窗一次虽能治标但不治本,为了不留坑,检查代码,发现问题所在如下代码中。
就是Activity
的setSoftInputMode()
设置了SOFT_INPUT_STATE_ALWAYS_VISIBLE
模式。
public static void showKeyboard(Activity activity, EditText editText) {
try {
if (activity != null && !activity.isFinishing()) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
// 此行代码引起的异常
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
if (editText != null) {
editText.requestFocus();
inputMethodManager.showSoftInput(editText, 0);
}
}
} catch (Exception ex) {
...
}
}
看看文档中对SOFT_INPUT_STATE_ALWAYS_VISIBLE
的描述
public static final int SOFT_INPUT_STATE_ALWAYS_VISIBLE Visibility state for softInputMode: please always make the soft input area visible when this window receives input focus.
Applications that target Build.VERSION_CODES.P and later, this flag is ignored unless there is a focused view that returns true from View#onCheckIsTextEditor() when the window is focused.
大致意思是,当前页面获取到焦点时会唤起软键盘。
在我的项目中Dialog
被唤起时,使用的是方法主动唤起,并把Activity
的软键盘模式设置成了SOFT_INPUT_STATE_ALWAYS_VISIBLE
,所以当Dialog
消失,Activity
重新获取焦点,键盘又被唤起了。
解决方法
解决方法有两种
- 避免使用
SOFT_INPUT_STATE_ALWAYS_VISIBLE
模式 - 用其他方法唤起软键盘,比如
fun showSoftInput(activity: Activity) {
val inputMethodManager: InputMethodManager =
activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
}
点赞、收藏mark一下✨✨万一用到时找不到了呢🌚