我遇到这种情况,我检查软键盘是否打开,我想在代码中解散,当我使用下面的代码时它无法解除键盘,因为代码找不到任何焦点,但键盘仍然是在,所以我怎么能隐藏它?
private void hideSoftKeyboard() {
Activity activity = (Activity) sContext;
View view = activity.getCurrentFocus();
if (view != null) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
//((Activity) sContext).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
} else {
Log.i(sClassTag,"focus not found");
}
}
答案 0 :(得分:6)
尝试使用此
您可以使用InputMethodManager
强制Android隐藏虚拟键盘,调用hideSoftInputFromWindow
,传入包含焦点视图的窗口的标记。
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
这将强制键盘在所有情况下都被隐藏。在某些情况下,您需要传递InputMethodManager.HIDE_IMPLICIT_ONLY
作为第二个参数,以确保在用户没有明确强制显示键盘时(通过按住菜单)隐藏键盘。
或者
InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
您可以找到更多详情here
答案 1 :(得分:0)
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
答案 2 :(得分:0)
您可以使用以下扩展名来切换键盘:
fun Context.showKeyboard() {
val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
}
fun Context.hideKeyboard() {
val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY)
}
fun Context.toggleKeyboard() {
val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
if (imm.isActive) {
hideKeyboard()
} else {
showKeyboard()
}
}