android - 未选择 edittext 时,onClick hideKeyboard 使该应用程序崩溃
问题描述
我正在尝试实现一个功能,当用户触摸虚拟键盘外部时,虚拟键盘就会从视图中消失。它可以工作,但是当未选择 edittext 时,它会导致应用程序崩溃。我尝试使用 try/catch 但这没有帮助。据我所知,它试图在没有打开键盘时关闭键盘。有什么建议么?
在 XML 文件中:
android:onClick="hideKeyboard"
在 Java 文件中:
public void hideKeyboard(View view) {
try {
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
catch (Exception e) {
}
}
解决方案
替换你的代码
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
和:
InputMethodManager imm=(InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
//Find the currently focused view, so we can grab the correct window token from it.
View view3=getCurrentFocus();
//If no view currently has focus, create a new one, just so we can grab a window token from it
if (view3==null){
view3=new View(this);
}
assert imm != null;
imm.hideSoftInputFromWindow(view3.getWindowToken(), 0);
推荐阅读
- scala - Scala语法规范不匹配if-else与一行表达式以分号结尾?
- vuelidate - 与 Vue 3 一起使用时出现 Vuelidate TypeError
- django - DRF 在视图集或序列化程序中创建方法
- php - 在数组中搜索或比较值
- c - FFMPEG libx265 编码在 avcodec_free_context 后未释放内存
- .net - BizTalk 中的 ISO schematron 验证有哪些替代方法?
- php - 使用相同的项目简化 PHP 数组
- android - Android 加密无法使用 KeyStore 解密数据 Generated kaypair KeyStoreException: Unknown error
- twilio - 使用谷歌语音到文本 API 覆盖文本
- asp.net-core - asp net core 3.1 Session永不过期