未选择编辑文本时,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);