首页 > 解决方案 > 隐藏软键板未知错误。我究竟做错了什么?

问题描述

我有一个带有三个 EditText 和一个按钮的活动。下面的代码写在按钮的 OnClickListener 中。

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

系统显示以下错误:

E/AndroidRuntime:致命异常:主要 java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法 'android.os.IBinder android.view.View.getWindowToken()'

标签: androidandroid-studioandroid-softkeyboard

解决方案


getCurrentFocus()在抛出此错误的情况下返回 null。试试下面的片段:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
View focus = getCurrentFocus();
if(focus == null) {
    focus = new View(this);
}
imm.hideSoftInputFromWindow(focus.getWindowToken(), 0);

推荐阅读