未选择 edittext 时,onClick hideKeyboard 会使该应用程序崩溃
onClick hideKeyboard crashes that app when edittext is not selected
我正在尝试实现一项功能,当用户触摸虚拟键盘外部时,虚拟键盘会从视图中消失。它可以工作,但是当未选择编辑文本时,它会导致应用程序崩溃。我尝试使用 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);
我正在尝试实现一项功能,当用户触摸虚拟键盘外部时,虚拟键盘会从视图中消失。它可以工作,但是当未选择编辑文本时,它会导致应用程序崩溃。我尝试使用 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);