Search code examples
androidandroid-activityandroid-softkeyboard

onClick hideKeyboard crashes that app when edittext is not selected


I'm trying to implement a feature where the virtual keyboard disappears from view when the user touches outside of it. It works, but when the edittext is not selected it causes the app to crash. I tried using a try/catch but that didn't help. From what I can tell, it's trying to close the keyboard when no keyboard is open. Any suggestions?

In the XML file:

android:onClick="hideKeyboard"

In the Java file:

public void hideKeyboard(View view) {
        try {
            InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
        catch (Exception e) {
        }
    }

Solution

  • Replace you code

     InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
      imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    

    with:

    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);