android - 隐藏软键板未知错误。我究竟做错了什么?
问题描述
我有一个带有三个 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()'
解决方案
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);
推荐阅读
- node.js - JointJS 依赖管理问题
- javascript - 如何根据输入值更改JS中的背景图像?
- python - 使用 docker for windows 对 ubuntu 进行 Dockerize
- sql - 无法弄清楚如何在 ORDER BY 子句中正确使用 CASE WHEN 语句
- android - 如何使用 Room 和带有 LiveData 的 ViewModel 检索树结构,以便在包含子 RecyclerView 的 RecyclerView 中使用?
- django - 如何修复在 html 中不显示表单小部件
- php - 如何在开发计算机上登录 Instagram
- php - 从php中定义的日期开始的日期增量
- php - phpfmt - 不要在私有和受保护的函数/变量之前添加 _
- excel - Excel 宏数据透视表刷新将 Err Number 设置为 40040 但成功 - 为什么?