如何解决未选择编辑文本时,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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。